Javascript 在ReactJS中,如何从父类更新子状态?
这是父类Javascript 在ReactJS中,如何从父类更新子状态?,javascript,reactjs,Javascript,Reactjs,这是父类 class Root extends React.Component { constructor(props) { super(props); this.state = { word: Words, }; } changeTheWord(i) { this.state.word.changeWord(i); } render() { return ( <div className="game">
class Root extends React.Component {
constructor(props) {
super(props);
this.state = {
word: Words,
};
}
changeTheWord(i) {
this.state.word.changeWord(i);
}
render() {
return (
<div className="game">
<ul>
<li><a href="#" onClick={() => this.changeTheWord('hey')}>Home</a></li>
<li><a href="">News</a></li>
<li><a href="">Contact</a></li>
<li><a href="">About</a></li>
</ul>
<this.state.word />
</div>
);
}
}
类根扩展React.Component{
建造师(道具){
超级(道具);
此.state={
字:字,
};
}
换词(一){
本.状态.字.换字(一);
}
render(){
返回(
);
}
}
这是儿童班
class Words extends React.Component {
constructor(props) {
super(props)
this.state = {
data: "read"
}
}
changeWord(i) {
this.state.data = i;
}
render() {
var sentence = "testing";
if (this.state.data != null) {
sentence = this.state.data;
}
return (
<div class="center">
<div class="words">
<p>{sentence}</p>
</div>
</div>
);
}
}
类单词扩展React.Component{
建造师(道具){
超级(道具)
此.state={
数据:“读取”
}
}
转换词(一){
this.state.data=i;
}
render(){
var语句=“测试”;
如果(this.state.data!=null){
句子=this.state.data;
}
返回(
{句子}
);
}
}
我试图做的是从父类根调用子类的changeWord方法,但由于某些原因,它不起作用,并且React给了我一个错误,TypeError:this.state.word.changeWord不是函数
这是负责调用函数的线路
<li><a href="#"onClick={ () => this.changeTheWord('hey')}>Home</a></li>
如何处理此问题?在您的示例中,
word
状态属性是用类Words
初始化的,而不是它的实例
相反,请尝试按如下方式初始化您的状态:
this.state = {
word: new Words()
}
你使用React的逻辑有点错误。为什么要将整个React组件(这里的子组件)保持在您的状态,并使用复杂而混乱的方法对其进行变异?React的逻辑非常简单明了。使用状态和道具,渲染子组件并在必要时将其传递给它。在进一步讨论之前,我强烈建议大家先读一下这本书 也许你想做这样的事情
类父级扩展React.Component{
建造师(道具){
超级(道具);
此.state={
数据:“默认语句”,
};
}
更改单词=(i)=>{
this.setState({data:i});
}
render(){
返回(
);
}
}
const Child=props=>(
-
-
-
-
{props.句子}
);
render(,document.getElementById(“根”))代码>
请阅读本节和整个页面,了解如何在React中改变状态<代码>this.state.data=i代码>是错误的。