Javascript 从ReactJS中的子对象访问父类方法
我有一个小问题,我有父类和子类。我想修改在父类中初始化的状态,以便可以在父类中看到更新的状态。代码如下:Javascript 从ReactJS中的子对象访问父类方法,javascript,reactjs,Javascript,Reactjs,我有一个小问题,我有父类和子类。我想修改在父类中初始化的状态,以便可以在父类中看到更新的状态。代码如下: var Parent = React.createClass({ getInitialState: function(){ return{ my_value: 0 } }, _increaseValue: function(){ this.state.my_value++; },
var Parent = React.createClass({
getInitialState: function(){
return{
my_value: 0
}
},
_increaseValue: function(){
this.state.my_value++;
},
render: function(){
return(
<div><Child /></div>
)
}
});
var Child = React.createClass({
render: function(){
//at button I want to access _increaseValue function of parent
return (
<div>
<button onClick={_increaseValue}>Increase</button>
</div>
);
}
});
var Parent=React.createClass({
getInitialState:函数(){
返回{
我的_值:0
}
},
_increaseValue:函数(){
this.state.my_value++;
},
render:function(){
返回(
)
}
});
var Child=React.createClass({
render:function(){
//在按钮处,我想访问父级的_increaseValue函数
返回(
增加
);
}
});
现在,当用户单击子类中的按钮时,我希望获得父类中更新的my_值
,因此我的问题是:
您需要通过道具将函数传递到子组件中。当需要更改时,调用此函数。这是正常的做法和反应方式 例如:
var Parent = React.createClass({
getInitialState: function(){
return{
my_value: 0
}
},
onChildClick: function() {
this.setState({
my_value: this.state.my_value + 1
})
},
render: function(){
return(
<div>
{this.state.my_value}
<Child onClick={this.onChildClick.bind(this)}/>
</div>
)
}
});
var Child = React.createClass({
_handleClick: function(){
this.props.onClick();
},
render: function(){
return (
<div>
<button onClick={this._handleClick}>Increase</button>
</div>
);
}
});
var Parent=React.createClass({
getInitialState:函数(){
返回{
我的_值:0
}
},
onChildClick:function(){
这是我的国家({
my_值:this.state.my_值+1
})
},
render:function(){
返回(
{this.state.my_value}
)
}
});
var Child=React.createClass({
_handleClick:function(){
this.props.onClick();
},
render:function(){
返回(
增加
);
}
});
props
将父方法传递给子方法,如下所示
var Parent = React.createClass({
getInitialState: function(){
return {
my_value: 0
}
},
onChangeValue: function () {
var value = this.state.my_value + 1;
this.setState({
my_value: value
})
},
render: function() {
return <div>
<Child
onChangeValue={ this.onChangeValue }
value={ this.state.my_value }
/>
</div>;
}
});
var Child = React.createClass({
_handleClick: function(){
this.props.onChangeValue();
},
render: function(){
return <div>
<h1> { this.props.value } </h1>
<button onClick={ this._handleClick }>Increase</button>
</div>
}
});
var Parent=React.createClass({
getInitialState:函数(){
返回{
我的_值:0
}
},
onChangeValue:函数(){
var值=this.state.my_值+1;
这是我的国家({
我的价值:价值
})
},
render:function(){
返回
;
}
});
var Child=React.createClass({
_handleClick:function(){
this.props.onChangeValue();
},
render:function(){
返回
{this.props.value}
增加
}
});
@阿米尔·艾尔:你能在你使用
道具的地方创造出“摆弄代码”吗?@阿米尔·艾尔:好的,我明白了