React refactor简单的输入组件

时间:2018-01-31 14:24:04

标签: javascript reactjs

我有多个需要输入值的组件 所以我在渲染方法上复制/粘贴以下代码:

 <input type="password"
             name="password" value={user.password}
             placeholder="password"
             onChange={e => this.handleChange(e)}/>

我在所有组件中复制/粘贴handleChange方法:

handleChange(event) {
 const {name, value} = event.target
 this.setState({
    [name]: value,
})
}

我想在组件中输入并从我的所有组件中调用它,然后获取输入值以将其添加到我当前的状态组件

你有解决方案吗?

由于

1 个答案:

答案 0 :(得分:0)

如果我理解正确你就不会这样:

class MyWrapperComponent extends React.Component {
  constructor(props) {
    this.state = { password: '' }
  }

  handleChange(event) {
    const {name, value} = event.target
    this.setState({
      [name]: value,
    })
  }

  render() {
    return (
      <div>
        <MyInputComponent value={this.state.password} onChange={this.handeChange.bind(this)} />
        <MyDisplayPasswordComponent password={this.state.password} />
      </div>
    )
  }
}

const MyInputComponent = (props) => {
  return (
    <input type="password"
           name="password" value={props.password}
           placeholder="password"
           onChange={props.onChange}/>
  )
}

const MyDisplayPasswordComponent = (props) => {
  return <h1>Your secret password is {props.password}</h1>
}