亲子沟通似乎没有什么问题:阵营使用道具通原生孩子家长的沟通
mainpage.ios.js代码:
var OtherPage = require('./otherpage');
<OtherPage value={2}/>
然后在otherpage.ios.js我可以用这个利用可变.props.value,但如果我更新otherpage.ios.js上的值,它将如何传回给mainpage.ios.js?
亲子沟通似乎没有什么问题:阵营使用道具通原生孩子家长的沟通
mainpage.ios.js代码:
var OtherPage = require('./otherpage');
<OtherPage value={2}/>
然后在otherpage.ios.js我可以用这个利用可变.props.value,但如果我更新otherpage.ios.js上的值,它将如何传回给mainpage.ios.js?
你会传递一个回调,然后将其穿过道具,有可能利用componentWillReceiveProps钩为您的安装变得更加先进。
如果你这样做很多,那么是的,你应该使用Flux或Redux或类似的。
import React, {
Component,
TouchableOpacity,
Text,
} from 'react-native';
class Main extends Component {
constructor() {
super();
this.state = {
data: 'default'
}
}
onChange = (data) => {
console.log(`Data changes to ${data} !`);
this.setState({ data });
}
render() {
const { data } = this.state;
return <Other data={data} onChange={this.onChange}></Other>;
}
}
class Other extends Component {
render() {
const { data } = this.props;
console.log(`Other Component Data is ${data}`);
return (
<TouchableOpacity onPress={() => {this.props.onChange('Success!')} }>
<Text style={{fontSize: 30}}>{data}</Text>
</TouchableOpacity>
);
}
}
此外,如果你使用静电元件,当你知道是不是需要在二级组件的状态,你可以建立更多的可重复使用的功能部件:
class Main extends Component {
constructor() {
super();
this.state = {
data: 'default'
}
}
onChange = (data) => {
console.log(`Data changes to ${data} !`);
this.setState({ data });
}
render() {
const { data } = this.state;
return <Other data={data} onChange={this.onChange}></Other>;
}
}
const Other = ({ data, onChange }) => {
return (
<TouchableOpacity onPress={() => {onChange('Success!')} }>
<Text style={{fontSize: 30}}>{data}</Text>
</TouchableOpacity>
);
}
非常有帮助。 非常感谢。 –
我强烈建议您在这里使用Flux。当你发现自己需要各种组件需要相同的信息时,那就意味着你需要Flux。你当然可以使用一堆回调等等,但随着你的应用程序的增长和变得越来越复杂,如果没有像流量那样管理它将会更加困难。
使用助焊剂时,您的主页面组件会监听更改,一旦发生更改,就会执行某些操作。例如:
mainpage:
componentDidMount() {
SomeStore.addChangeListener(this.updateComponent)
}
componentWillUnmount() {
SomeStore.removeChangeListener(this.updateComponent)
}
updateComponent() {
this.setState value: SomeStore.getValue()
}
otherpage:
toggle() {
SomeActions.change(this.props.value + 1)
}
render() {
<TouchableOpacity onPress={this.toggle}>
<View>Some View</View>
</ToucableOpacity>
}
我不同意这里。像助焊剂/还原剂/回流剂这样的国家商店不会否定对儿童 - >父母沟通的需求。如果你有聪明和愚蠢的组件,就像现在通常推荐的那样,你的智能组件知道状态存储,而哑子只是显示内容并呼叫给父母。 –
http://stackoverflow.com/a/33721002/4481883 – Phyo
http://andrewhfarmer.com/component-communication/ –
是的,我看过那篇文章,但其中并没有那么清楚。第二个是关于React而不是React Native。 – Hasen