我创建了三个基本组件.
A渲染组件B和C B就像标题包含标签1,2,3 C是第一页,其中有两种形式,一次显示一个.在显示第一个表单时,我需要在B组件中显示选项卡1.在显示第二个表单时,我需要在B组件中显示选项卡3.
我只想根据哪个表单显示给B组件从C组件传递数据.
我把状态放在C组件上并尝试使用相同的this.state.data或this.props.data,因为B控制器中没有值.
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;
Run Code Online (Sandbox Code Playgroud)
B.jsx
import React from 'react';
class B extends React.Component {
constructor(props) {
super(props);
this.state = {
show : '1',
}
}
render() {
return (
//html code here
)
}
}
Run Code Online (Sandbox Code Playgroud)
C.jsx
class C extends React.Component {
constructor(props) {
super(props);
this.state = {
show : '1',
}
}
render() {
return (
//html code here
)
}
}
Run Code Online (Sandbox Code Playgroud)
你需要将你的状态添加到父组件这里它将是一个组件然后传递一个函数来改变你的状态到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>
)
}
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以访问子组件中的显示状态,并可以从中更改它,例如在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>
)
}
}
Run Code Online (Sandbox Code Playgroud)
现在您可以访问B中的显示状态
class B extends React.Component {
render() {
return (
{this.props.show}
)
}
}
Run Code Online (Sandbox Code Playgroud)
在你的例子中你想要做什么并不清楚,所以我试图举例说明如何在一般意义上在子组件之间传递状态.我希望它足够有用
| 归档时间: |
|
| 查看次数: |
14354 次 |
| 最近记录: |