reactjs 如何使用点击事件更改父 prop 的值?[副本]

7ajki6be  于 2023-05-17  发布在  React
关注(0)|答案(3)|浏览(145)

此问题已在此处有答案

How can I update the parent's state in React?(24回答)
2小时前关闭
我尝试使用React的componentWillUnmount功能,并通过click事件从子组件更改prop的值。我想我愿意使用“提升状态”,并希望使用React的componentWillUnmount属性。

export default class App extends React.Component {
  constructor(props){
    super(props);
    this.state={
      show:true
    }
  }
  render() {
    const toggleDisplay=()=>{
      this.setState({show:!this.state.show});
    }
    return (
      <div className="App">
        {this.show&&<ChildrenUnmounting onclickfun={toggleDisplay} />}
      </div>
    );
  }
}
class ChildrenUnmounting extends React.Component {
  constructor(props) {
    super(props);
    alert("constructor is called!");
    this.state={
      onclickfun:props.onclickfun,
    }
    alert("constructor is called!");
  }

  render() {
    return (
      <>
        {alert("render is called!")}

        <h1>This content is shown!</h1>
        <button onClick={this.state.onclickfun}>
          Toggle View
        </button>
      </>
    );
  }

  componentWillUnmount() {
    alert("componentWillUnmount is called!");
  }
}
zzoitvuj

zzoitvuj1#

在Appcomponent的render()方法中,使用的是this.show而不是this.state.show。更新行

{this.show&&<ChildrenUnmounting onclickfun={toggleDisplay} />}

{this.state.show && <ChildrenUnmounting onclickfun={toggleDisplay} />}.

通过此更改,show state属性将在render()方法中正确引用,并且将根据其值显示或隐藏子组件。

4nkexdtk

4nkexdtk2#

App组件的返回函数中,条件具有不正确的变量(this.show代替了this.state.show)。正因为如此,你正面临着这样的问题。
当前代码:

{this.show && <ChildrenUnmounting onclickfun={toggleDisplay} />}
/*^^^^^^^*/

像这样更新:

{this.state.show && <ChildrenUnmounting onclickfun={toggleDisplay} />}
/*^^^^^^^^^^^^^*/
mnowg1ta

mnowg1ta3#

您没有正确地将状态设置器向下传递给子组件。相反,您将其设置为状态值/变量。
代码应该是这样的:

export default class App extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      show: true
    }
  }

  const toggleDisplay = () => {
    this.setState({ show:!this.state.show });
  }

  render() {
    return (
      <div className="App">
        {this.state.show && <ChildrenUnmounting onclickfun={toggleDisplay} />}
      </div>
    );
  }
}

class ChildrenUnmounting extends React.Component {
  constructor(props) {
    super(props);
    alert("constructor is called!");
  }

  render() {
    return (
      <>
        {alert("render is called!")}

        <h1>This content is shown!</h1>
        <button onClick={this.props.onclickfun}>
          Toggle View
        </button>
      </>
    );
  }

  componentWillUnmount() {
    alert("componentWillUnmount is called!");
  }
}

相关问题