javascript - 在react中将onChange传递给子组件

标签 javascript reactjs ecmascript-6 react-props

我有一个 React 组件,我想将 onChange 作为 prop 传递给子组件,我使用原子设计,这是我的代码:

HeadComponent.js

class Headcomponent extends React.Component{

  constructor (props) {

    super(props);
    this.state = {
      email: '',
      password: '',
      formErrors: {email: '', password: ''},
      emailValid: false,
      passwordValid: false,
      formValid: false,
      items: [],

    }
  }

  handleUserInput = (e) => {

    const name = e.target.name;
    const value = e.target.value;
    this.setState({[name]: value},
                  () => { this.validateField(name, value) });
  }

render(){

    const fields= [
    {
      label: 'hhdghghd',
      placeholder: 'fhfhhfhh 1',
      ExampleMessage: this.state.formErrors.email ,
      ErrorMessage: 'error message for input 1',
      inputValue: this.state.email,
      onChange: this.handleUserInput  //this is where I'm passing my function


    },
    {
      label: 'fffff',
      placeholder: 'tttttt 2',
      ExampleMessage: 'example message  for second label',
      ErrorMessage: 'error message for input 2',
      onChange: this.handleUserInput


    },
  ]

return (
    <div>

  <Form fields={fields} buttonText="Submit"/>

    </div>
        );
    }

}

export default Headcomponent;

Form.js

    const Form = props => (
      <form className="Form">
        {
          props.fields.map((field, i) => (<LabeledInput label={field.label}
           placeholder={field.placeholder}
           ExampleMessage={field.ExampleMessage}
           ErrorMessage={field.ErrorMessage}
           onChange= {(e)=> field.onChange}
           inputValue= {field.inputValue}
           key={i}
           passwordError={props.passwordError}

           />))
        }
        <Button text={props.buttonText} />
      </form>
    );

    Form.propTypes = {
      fields: PropTypes.arrayOf(PropTypes.object).isRequired,
      buttonText: PropTypes.string.isRequired,
    };

    export default Form;

标签输入

const LabeledInput = props => (
  <div className={`form-group `} >
    <Label text={props.label} />
    <Input inputValue={props.inputValue} placeholder={props.placeholder} type="text" onChange={(e)=> props.onChange} />

    <ErrorMessage text={props.ErrorMessage} />
    <ExampleMessage ExampleMessage={ props.ExampleMessage} />
  </div>
);

LabeledInput.propTypes = {
  label: PropTypes.string.isRequired,
  placeholder: PropTypes.string,
  onChange: PropTypes.func.isRequired,
  //value: PropTypes.string.isRequired,
  exampleText: PropTypes.string,
};
export default LabeledInput;

Input.js

const Input = props => (
  <input type={props.type} class="form-control form-control-success is-valid" placeholder={props.placeholder} value={props.inputValue} className="form-control form-control-success"
      onChange={ (e)=> props.onChange } />
);

Input.propTypes = {

  inputValue: PropTypes.string,
  type: PropTypes.string,
  placeholder: PropTypes.string,
  onChange: PropTypes.func.isRequired,
};

export default Input;

如何将 handleUserInputHeadComponent.js 传递到 Input.js,到目前为止使用 props 我无法让它触发更改文本时。

最佳答案

您忘记实际调用 field.onChange 方法。而不是:

onChange= {(e)=> field.onChange}

您可以将其更改为:

onChange= {field.onChange}

我还注意到您的 handleUserInput 设置状态为:

{ [name]: e.target.value }

但是,您没有将 name 设置为任何输入,这是行不通的。

请看一下我的工作示例:

const LabeledInput = props => (
  <div className="form-group">
    <label>{props.label}</label>
    <input
      className="form-control"
      type="text"
      placeholder={props.placeholder}
      onChange={props.onChange} // That's how you have to call onChange
      name={props.name} // You are not setting this prop
    />
    <div>{props.ErrorMessage}</div>
    <div>{props.ExampleMessage}</div>
  </div>
)

const Form = ({ buttonText, fields }) => (
  <form className="Form">
    {fields.map((field, i) => <LabeledInput key={i} {...field} />)}
    <button className="btn btn-primary">{buttonText}</button>
  </form>
)

class Headcomponent extends React.Component {
  constructor() {
    super()

    this.state = {
      email: '',
      password: '',
      formErrors: {email: '', password: ''},
      emailValid: false,
      passwordValid: false,
      formValid: false,
      items: [],
    }

    this.handleUserInput = this.handleUserInput.bind(this)
  }
  
  handleUserInput(e) {
    const name = e.target.name
    const value = e.target.value
    // Now that you have `name` and `value`, state updates are going to work
    this.setState({
      [name]: value
    })
  }

  render() {
    const fields = [
      {
        label: 'Email',
        placeholder: 'email placeholder',
        ExampleMessage: this.state.formErrors.email ,
        ErrorMessage: 'error message for input 1',
        inputValue: this.state.email,
        onChange: this.handleUserInput,
        name: 'email',
      },
      {
        label: 'Password',
        placeholder: 'password placeholder',
        ExampleMessage: 'example message  for second label',
        ErrorMessage: 'error message for input 2',
        onChange: this.handleUserInput,
        name: 'password',
      },
    ]
    
    return (
      <div>
        <Form fields={fields} buttonText="Submit"/>
        
        <div style={{ marginTop: 20 }}>
          <div>state.email: {this.state.email}</div>
          <div>state.password: {this.state.password}</div>
        </div>
      </div>
    )
  }
}

ReactDOM.render(
  <Headcomponent />,
  document.getElementById('root')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div id="root"></div>

关于javascript - 在react中将onChange传递给子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48731478/

相关文章:

javascript - 如何在 ReactJS 中通过对象数组过滤数组项?

javascript - 无法接收作为 json 传输到 js 的 python 对象的属性

javascript - 在 ejs 中制作类似组件的元素

javascript - 使用正确的后备路由结构从 Nodejs 中的异步调用传递数据的最佳实践

reactjs - 如何将子组件的表单值传递给父组件

javascript - 如何在 JavaScript 2015 (EcmaScript 6) 中给它取别名?

javascript - 如何将字符串的每个字母保存在不同的数组位置?并组合回单个字符串?

javascript - 执行NPM脚本时出现语法错误

javascript - React.js 中功能组件内部的反跳

javascript - 导入 es6 模块,一些命名导出未定义