简体   繁体   English

如何将状态作为道具传递,以便您可以对其进行修改

[英]How to pass state as props so you can modify them

I have a main class here that holds three states rendering a Form component: 我这里有一个主类,其中包含三个状态,这些状态呈现一个Form组件:

class MainApp extends React.Component{
 constructor(props){
   super(props);

   this.state = {
     fName: '',
     lName: '',
     email: ''
 }

render(){
  return(
     <div className="content">
          <Form formState={this.state}/>
     </div>
  )
}
}

And then inside my Form component I have ff codes: 然后在我的Form组件中,我有ff代码:

class Form extends React.Component{
     constructor(props){
       super(props);

     }

    render(){
      return(
         <form>
            <input placeholder="First Name" value={this.props.formState.fName}
             onChange={e => this.setState({ this.props.formState.fName: e.target.value })}
         </form>
      )
    }
    }

Upon running this codes, I got an error saying it cannot read the property 'fName' of null. 运行此代码后,出现错误,提示它无法读取null的属性'fName'。

How do I properly pass one state to it's children component so it can modify the main one? 我如何正确地将一种状态传递给它的子组件,以便它可以修改主状态?

        class MainApp extends React.Component{
         constructor(props){
           super(props);

           this.state = {
             fName: '',
             lName: '',
             email: ''
         }
          this._handleChange = this._handleChange.bind(this);
        }

     //dynamically update the state value using name 

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

        render(){
          return(
             <div className="content">
                //You can pass state and onchange function as params
                  <Form formState={this.state} _handleChange={this._handleChange}/>
             </div>
          )
        }
        }



   class Form extends React.Component{
        constructor(props){
          super(props);
       }

        render(){
           return(
            <form>
                <input placeholder="First Name"
                 defaultValue={this.props.formState.fName} 
                 id="fName"
                 name="fName"
                 onChange={e => this.props._handleChange} />
            </form>
         )
       }
     }

You can't edit parent's state directly from child component. 您不能直接从子组件中编辑父状态。 You should define handlers that would change parent's state in parent component itself, and pass them to children via props. 您应该在父组件本身中定义将更改父状态的处理程序,然后通过prop将其传递给子级。

Parent: 家长:

class MainApp extends React.Component{
 constructor(props){
   super(props);
   this.state = {
     fName: '',
     lName: '',
     email: ''
   }

   fNameOnChange = (value) => {
     this.setState({fName:value})
   }

   render(){
     return(
       <div className="content">
         <Form formState={this.state} fNameChange={this.fNameOnChange}/>
       </div>
     )
  }
}

Child: 儿童:

class Form extends React.Component{
 constructor(props){
   super(props);
 }

 render(){
   return(
      <form>
        <input placeholder="First Name" value={this.props.formState.fName}
        onChange={e => this.props.fNameChange(e.target.value))}
      </form>
    )
  }
}

You should pass a function as a prop to update the state of parent component. 您应该传递一个函数作为道具来更新父组件的状态。 It is advised not to change props directly. 建议不要直接更换道具。

In your parent class write a function like: 在您的父类中编写一个类似以下的函数:

onChangeHandler (data) {
  this.setState({fname: data})
}

And pass it to the child component and you can call this method as this.props.onChangeHandler(event.target.data) from child component. 并将其传递给子组件,您可以从子组件中将此方法称为this.props.onChangeHandler(event.target.data)

Thanks 谢谢

I'm wondering why you want to pass a formState to the form itself. 我想知道为什么要将formState传递给表单本身。 The form should manage is own state. 表格应该管理的是自己的状态。 It is not a good practice to do 2 way binding like the Form mutate the MainApp's state 进行两种方式绑定(如Form突变MainApp的状态)不是一个好习惯

However, if for some reasons you need a copy of you formState in your MainApp component, then your Form component should have an onSubmit callback method. 但是,如果由于某些原因在MainApp组件中需要formState的副本,则Form组件应具有onSubmit回调方法。

 class MainApp extends React.Component{ constructor(props){ super(props); this.state = { form: null } } render() { return( <div className="content"> <Form onSubmit={(form) => { this.setState({ form }); })}/> </div> ) } } class Form extends React.Component{ constructor(props){ super(props); this.state = { fName: '', lName: '', email: '' } } render(){ return( <form onSubmit={e => this.props.onSubmit(this.state) }> <input placeholder="First Name" value={this.props.formState.fName} onChange={e => this.setState({ this.props.formState.fName: e.target.value })} </form> ) } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM