好吧,假设我有一个类似的组件:
由2个不同的组成部分组成:
1)整个矩形(我们称之为card
)
2)每一面(正方形)是另一个组成部分(我们称之为cardSide
)
我在card
上添加了一个按钮,当点击它时,它会收集每个cardSide
组件(文本,注释,图像等)的所有信息。
我的问题是,我怎样才能做到这一点?我读过关于passing refs from parent to children
和sending props from parent to children
的内容,但我没有找到任何相反的getting the props/states from children components
的例子。
我没有太多关于React的经验,我在Java
中使用钩子和函数而不是类(如果有意义),通过访问get methods of each instance
很容易做到这一点,如何在React中完成?
看到这个网址:qazxsw poi。并阅读rossipedia的答案。
似乎“使用类组件(> = [email protected])”部分对您更有用。
您需要在父容器中创建一个设置状态的函数/方法。从那里你可以将它传递给子组件,它将能够设置其父级的状态。
为了实现这种通信,我建议孩子(CardSide Component)通过Events与Card Component通信。
因此,当用户在卡片组件上完成操作时会触发一个事件,将所有数据传递给父母,让我向您展示一个我的意思的示例:
卡组件
Call child method from parent
CardSide组件
class Card extends Component {
handleCompelete = data => {
//the data here are all the data entered from the child component
//do some sorting using table name
};
render() {
return <CardSide onCompelete={this.handleCompelete} />;
}
}
编辑
您无法访问子组件的状态,因为它是私有组件。
关于props,您可以访问它,但它是从父组件传递的ReadOnly,但子组件不能修改它。
实际上有一种方法来访问组件子(但我发现它会使你的代码复杂化而不是简化它,我不建议这样做)
让我们说这是你app.js
class CardComponent extends Component {
render() {
return (
<div>
{/* data here reprensets what you need to transfer to parent component */}
<button onClick={() => this.props.onCompelete(data)} />
</div>
);
}
}
正如你所看到的,我将CardSide与名称someProp作为卡片rathar的子项包含在内,而不是将其插入卡片组件中
在Card Component中,我访问了children属性,如下所示:
class App extends Component {
constructor() {
super();
this.state = {
name: "React"
};
}
render() {
return (
<div>
<h1>Title</h1>
<Card>
<CardSide someProp="My Child Prop Value" />
</Card>
</div>
);
}
}
和CardSide组件
class Card extends Component {
handleCompelete = data => {
//the data here are all the data entered from the child component
//do some sorting using table name
};
render() {
return <div>
{this.props.children}
{console.log(this.props.children)}
{this.props.children.props.someProp}
</div>;
}
}
正如您所看到的,它将使您的结构更加复杂,如果没有密集跟踪,很难知道谁是卡组件的子项。
你可以通过这个链接class CardSide extends Component {
render() {
return (
<div>
{/* data here reprensets what you need to transfer to parent component */}
<button onClick={() => this.props.onCompelete(data)} >
Hello btn
</button>
</div>
);
}
}
查看代码