【问题标题】:Update a prop in a child component after an event in parent component?在父组件中的事件之后更新子组件中的道具?
【发布时间】:2019-10-23 17:25:29
【问题描述】:

取2个分量:

父组件 子组件

ParentComponent 在 render 中设置 ChildComponent:

render() {
    return (
        <ChildComponent x='default value' />
    )
}

然后,ParentComponent 想要将 x='default value' 更改为 'hello',可能是为了响应 onClick 事件。

我认为我的困惑是,我知道如何设置初始变量 x,但不知道以后如何更改它。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您可以在Parent 状态下管理它,然后将状态值作为道具传递给Child。

    子组件。

    const ChildComponent = props => {
       return <div>{props.x}</div>;
    };
    

    父组件

    class Parent extends Component {
      constructor(props) {
        super(props);
        this.state = {
           x: "default value"
        };
    }
    
    changeX = x => {
       this.setState({
          x: x
       });
    };
    
    render() {
      return (
        <div>
         <ChildComponent x={this.state.x} />
         <button
            onClick={() => {
              this.changeX("x");
           }}
         >
           Change X
         </button>
        </div>
       );
     }
    }
    

    这里是codepen。

    【讨论】:

      【解决方案2】:

      将您的状态提升到您的Parent 并通过props 将其传递给Child

      const Parent = () =>{
          const [title, setTitle] = useState('foo')
      
          return(
              <>
                  <Child title={title} />
                  <button onClick={() => setTitle('bar')}>Change to bar</button>
              </>
          )
      }
      
      const Child = ({ title }) => <div>{title}</div>
      

      对于基于class 的组件

      class Parent extends React.Component {
          state = { title: 'foo' }
      
          render() {
              const { title } = this.state
              return (
                  <>
                      <button onClick={() => this.setState({ title: 'bar' })}>Change to bar</button>
                      <Child title={title} />
                  </>
              )
          }
      }
      
      class Child extends React.Component {
          render() {
              const { title } = this.props
              return <div>{title}</div>
          }
      }
      

      【讨论】:

      • 假设状态将共享给许多子组件,那么术语提升状态是适用的。否则,它只是将状态作为道具传递。你这么认为?
      • 提升状态就是这个意思。将状态提升到组件树中的更高位置。你只需要一个层次关系就可以成为一个有效的术语
      猜你喜欢
      • 1970-01-01
      • 2019-12-09
      • 2021-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-01
      • 2019-07-08
      • 2019-12-19
      相关资源
      最近更新 更多