【问题标题】:How would I structure react components that must receive data from a modal我将如何构建必须从模态接收数据的反应组件
【发布时间】:2016-10-01 23:46:51
【问题描述】:

现在我的 React 容器看起来像这样:

class TableData extends Component
{
some React Functions and state changes. 
<Sidebar passdata as props/>

}

在侧边栏内我有一个模式,需要更新侧边栏组件和 TableData 组件的状态。

我不知道你是否可以在 React 中将 props 传递给父组件,但我知道不推荐这样做。在这些类型的问题中推荐的行动方案是什么?

【问题讨论】:

  • 你使用的是 redux 还是类似的东西?
  • 目前不是,我应该是吗?我只有这两个组件我有这个问题
  • Redux 对于大型项目很有用,但对于小规模的项目则不是必需的。

标签: javascript reactjs jsx


【解决方案1】:

您是正确的,您不能将道具传递给父组件。但是,父组件可以将回调作为 prop 传递给其子组件,当值更改时调用该回调。

class TableData extends React.Component {

    constructor(props) {
        // ...
        this.state = {
            name: originalState,
        };
    }

    handleStateChange(newState) {
        this.setState({ name: newState });
    }

    render() {
        // ...
        <Sidebar onStateChange={this.handleStateChange.bind(this)} />
        // ...
    }
}

class Sidebar extends React.Component {
    // ...
    this.props.onStateChange(newState);
    // ...
}

【讨论】:

    猜你喜欢
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2019-12-09
    • 2019-05-29
    • 2021-03-29
    • 1970-01-01
    • 2021-04-05
    • 2018-08-12
    相关资源
    最近更新 更多