如何访问另一个类的状态。
此构造不起作用
class classname2 extends React.Component {
...
this.state = { statename1: "lala" };
...
};
class classname1 extends React.Component {
render() {
return (
{classname2.state.statename1 }
);
}
};
最佳答案
正如评论中提到的,将状态作为 Prop 传递给他们的 child 。
class classname2 extends React.Component {
this.state = { statename1: "lala" };
render() {
return <classname1 statename1={this.state.statename1} />
}
};
class classname1 extends React.Component {
render() {
return (
<div>{this.props.statename1}</div>
);
}
};
一种常用的模式是沿着组件树传递任意 Prop :
const {needThisOne, andThisOne, ...props} = this.props;
// do stuff with needThisOne andThisOne
// and pass the remaining props down:
return <Component {...props} />;
<小时/>
钩子(Hook)的更新,因为为什么不呢。
const ParentComponent = ({...props}) => {
const [stateName1, setStateName1] = useState('defaultValue');
return <ChildComponent stateName1={stateName1} {...props} />;
}
const ChildComponent = ({stateName1, ...props}) => (
<span>{stateName1}</span>
);
关于javascript - React js访问另一个类的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45664988/