We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
来源:React 进阶实战指南
class Form extends React.Component{ state={ formData:{} } /* 用于提交表单数据 */ submitForm=(cb)=>{ cb({ ...this.state.formData }) } /* 获取重置表单数据 */ resetForm=()=>{ const { formData } = this.state Object.keys(formData).forEach(item=>{ formData[item] = '' }) this.setState({ formData }) } /* 设置表单数据层 */ setValue=(name,value)=>{ this.setState({ formData:{ ...this.state.formData, [name]:value } }) } render(){ const { children } = this.props const renderChildren = [] React.Children.forEach(children,(child)=>{ if(child.type.displayName === 'formItem'){ const { name } = child.props /* 克隆`FormItem`节点,混入改变表单单元项的方法 */ const Children = React.cloneElement(child,{ key:name , /* 加入key 提升渲染效果 */ handleChange:this.setValue , /* 用于改变 value */ value:this.state.formData[name] || '' /* value 值 */ },child.props.children) renderChildren.push(Children) } }) return renderChildren } } /* 增加组件类型type */ Form.displayName = 'form'
function FormItem(props){ const { children , name , handleChange , value , label } = props const onChange = (value) => { /* 通知上一次value 已经改变 */ handleChange(name,value) } return <div className='form' > <span className="label" >{ label }:</span> { React.isValidElement(children) && children.type.displayName === 'input' ? React.cloneElement(children,{ onChange , value }) : null } </div> } FormItem.displayName = 'formItem'
/* Input 组件, 负责回传value值 */ function Input({ onChange , value }){ return <input className="input" onChange={ (e)=>( onChange && onChange(e.target.value) ) } value={value} /> } /* 给Component 增加标签 */ Input.displayName = 'input'
The text was updated successfully, but these errors were encountered:
No branches or pull requests
Form
FormItem
Input
The text was updated successfully, but these errors were encountered: