gpt4 book ai didi

reactjs - React.js 在组件之间传递数据流

转载 作者:行者123 更新时间:2023-12-03 13:40:08 24 4
gpt4 key购买 nike

我创建了三个基本组件。

A 渲染组件 B 和 CB 就像包含选项卡 1,2,3 的 header C 是第一页,有两个表格,一次显示一个。在显示第一个表单时,我需要在 B 组件中显示选项卡第一个 1。在显示第二种形式时,我需要在 B 组件中显示选项卡 3。

我只想根据显示的表单将 C 组件的数据传递给 B 组件。

我将状态放在 C 组件上,并尝试使用相同的 this.state.data 或 this.props.data,因为 B Controller 中没有任何值。

A.jsx

import React from 'react';
import B from './B.jsx';
import C from './C.jsx'
class A extends React.Component {
constructor(props) {
super();
this.state = {
show : '1',
}
}
render() {
return (
<div>{this.props.show}
<B />
<C/>
</div>
)
}
}

export default A;

B.jsx

import React from 'react';

class B extends React.Component {
constructor(props) {
super(props);
this.state = {
show : '1',
}
}
render() {
return (
//html code here
)
}
}

C.jsx

class C extends React.Component {
constructor(props) {
super(props);
this.state = {
show : '1',
}
}
render() {
return (
//html code here
)
}
}

最佳答案

您需要将状态添加到父组件(此处为 A 组件),然后传递一个函数将您的状态更改为 B 和 C,以更改 A 上的状态,如下所示

class A extends React.Component {
constructor(props) {
super();
this.state = {
show : '1',
};
}
changeShow(show){
this.setState({show: show});
}
render() {
return (
<div>{this.props.show}
<B show={this.state.show}/>
<C handleChangeShow={this.changeShow.bind(this)} show={this.state.show}/>
</div>
)
}
}

现在您可以访问子组件中的显示状态,并可以从子组件中更改状态,例如在 C 中

class C extends React.Component {
handleChange({target}){
this.props.handleChangeShow(target.value)
}
render() {
return (
<select onChange={this.handleChange.bind(this)}>
<option value="0">hide</option>
<option value="1">show</option>
</select>
)
}
}

现在您可以在 B 中显示状态

class B extends React.Component {

render() {
return (
{this.props.show}
)
}
}

您在示例中想要做什么还不够清楚,因此我尝试给出一个示例,说明如何在一般意义上在子组件之间传递状态。我希望它足够有用

关于reactjs - React.js 在组件之间传递数据流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41676254/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com