子组件中有个状态需要在父组件中用到,那么父组件如何能做到实时响应?
目前能想到的办法是利用回调,能不能在父组件中直接获取子组件的状态?比如用 this.refs.xxx.state.xxx 这样获取的并不是实时的,能获取实时的吗?像 redux 这样,能做到实时响应,而不需要额外处理?
子组件中有个状态需要在父组件中用到,那么父组件如何能做到实时响应?
目前能想到的办法是利用回调,能不能在父组件中直接获取子组件的状态?比如用 this.refs.xxx.state.xxx 这样获取的并不是实时的,能获取实时的吗?像 redux 这样,能做到实时响应,而不需要额外处理?
class Parent extends React.Component {
render() {
return (
<div>
<Child onChange={this.getChildState} />
</div>
)
}
/** 获取子组件状态 */
getChildState = (state) => {
console.log(state);
}
}
import PropTypes from 'prop-types';
class Child extends React.Component {
static propsType = {
onChange: PropTypes.func
}
// .....
}你不想用回调,也不想使用refs。那么只好用redux了。
在子组件中,直接将state交给redux。父组件直接从redux中获取就好了。
另外,你的refs不是实时数据,估计是你哪里出问题了。这个不应该。refs获取到的数据就是它指向的组件的当前状态。
4 回答575 阅读✓ 已解决
1 回答648 阅读
1 回答646 阅读
查查
getChildContext