我希望有一个用户对象,它将是react组件,这样它就可以渲染它的配置文件。但我也想访问它的状态,在需要的时候从其他组件。我想定义一些可以作为getter使用的方法。所以我想做像这样的事情
const User = module.exports = React.createClass({
propTypes: {
GoogleUser: React.PropTypes.object
},
getInitialState(){
return {
name: 'John Doe',
email: 'john@mail.com',
id: 123
};
},
render(){
return '<span>'+this.state.name+'</span>';
},
Profile(){
return {
name: this.state.name,
email: this.state.email
};
}
});
但是,当我将创建的元素作为参数传递并访问Profile()
方法时,它是未定义的。我如何才能以一种直接且尽可能少的代码访问用户的方式来做到这一点呢?
发布于 2016-02-19 19:45:59
有两种方法可以实现这一点。最常用的方法是将更改侦听器传递给组件,每当组件状态发生更改时都会通知该侦听器。
其基本思想是将回调属性传递给组件,并在状态发生变化时更新该回调。所以你会有像这样的东西
propTypes: {
//parent component will declare and pass this observer
onStateChange: React.PropTypes.func
},
getDefaultProps() {
return {
//declare default null function
onStateChange: () => null,
};
},
//call this function whenever a change is made to the state
handleStateChange(newState) {
onStateChange(newState);
}
实现这一点的另一种方法是公开一个函数并使用refs访问它。请参见React文档中的Expose Component Functions。这种方式更接近于您在上面粘贴的代码,但它不太常用,并且有点背离了React范例。我的建议是真正尝试让回调方法在您的应用程序体系结构中工作,而且只有在您确定它不是使用公开组件函数方法的正确解决方案的情况下。
https://stackoverflow.com/questions/35513265
复制相似问题