【问题标题】:How to Set a state of parent component from child component in react js如何在反应js中从子组件设置父组件的状态
【发布时间】:2018-11-07 06:15:38
【问题描述】:
 how do i  change the state of parent in child component
I'm trying to create a popover in react 

Parent component

    class App extends Component {
      constructor(props) {
        super(props);
        this.state = {
          status: false,
          anchorEl: null
        };
      }

      showpop = () => {


        this.setState({ status: !this.state.status });
      };


    render() {
        return (

            <React.Fragment>
              <p id="popup" onClick={this.showpop}>
                Click me
              </p>
              {this.state.status ? (
                <Popup status={this.state.status}>test</Popup>
              ) : (
                ""
              )}
            </React.Fragment>
        );
      }
    }

我只是将 status 的状态传递给 popover 组件。 这是子组件

export default class popup extends Component {
  constructor(props) {
    super(props);
    this.state = {
      popupStatus: false
    };
  }

  componentWillMount() {
    document.addEventListener("click", this.handleclick, false);
  }
  componentWillUnmount() {
    document.removeEventListener("click", this.handleclick, false);
  }


  handleclick = e => {
    if (this.node.contains(e.target)) {
      return;
    } else {

//这里怎么办?

    }
  };

  render() {
    return (
      <React.Fragment>
        <Mainbox
          status={this.props.status}
          ref={node => {
            this.node = node;
          }}
        >
          {this.props.children}
        </Mainbox>
      </React.Fragment>
    );
  }
}

在handleclick函数的其他部分, 我试过这些 我将节点样式显示更改为无,但在窗口中需要单击两次才能显示弹出框

您可以看到子组件中的 Mainbox 组件是使用 styed 组件库创建的

有没有办法隐藏元素并改变父状态?

【问题讨论】:

  • 您可以将更新状态的方法作为道具传递给孩子并从那里调用它。
  • 请解释一下我已经尝试通过该方法但如何更改状态

标签: reactjs


【解决方案1】:

你可以只传递一个方法引用给孩子:

<Popup status={this.state.status} showpop={this.showpop}>test</Popup>

  handleclick = e => {
    if (this.node.contains(e.target)) {
      return;
    } else {
      this.props.showpop()
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-14
    • 2018-09-08
    • 1970-01-01
    • 2021-01-23
    • 2021-06-27
    相关资源
    最近更新 更多