一、采用正常的state方式
import AppUserNameItemState from './AppUserNameItemState';
import AppUserAgeItemState from './AppUserAgeItemState';
class App extends Component {
constructor(props){
super(props)
this.state = {
userName: "精神病患者",
userAge: '18',
}
}
render() {
console.log('app render',this.state)
return (
<View style={styles.container}>
<View>
<AppUserNameItemState data={this.state.userName} changeText={(value)=>{
this.setState({
userName: value
})
}}/>
<AppUserAgeItemState data={this.state.userAge} changeText={(value)=>{
this.setState({
userAge: value
})
}}/>
</View>
</View>
);
}
}
class AppUserAgeItemState extends Component {
render() {
console.log('AppUserAgeItemState render')
return (
<View style={{flexDirection: "row", marginTop: 20}}>
<Text style={{width: 100}}>你的年龄:</Text>
<TextInput value={String(this.props.data)} onChangeText={(value)=>{
this.props.changeText(value)
}}/>
</View>
);
}
}
class AppUserNameItemState extends Component {
render() {
console.log('AppUserNameItemState render')
return (
<View style={{flexDirection: "row", marginTop: 20}}>
<Text style={{width: 100}}>你的名字:</Text>
<TextInput value={String(this.props.data)} onChangeText={(value)=>{
this.props.changeText(value)
}}/>
</View>
);
}
}
程序刚运行完毕
修改名字(没有修改年龄,但是走了AppUserAgeItemState
的render
方法)
修改年龄(没有修改名字,但是走了AppUserNameItemState
的render
方法)
二、采用mobX的 observer observable 方式
const myStore = observable({
userName: "精神病患者",
userAge: 18,
userSex: 0, // 0 男 1 女
/**
* 修改年龄
* age 要修改的年龄
*/
changeUserAge(age) {
this.userAge = age;
},
/**
* 修改姓名
* age 要修改的年龄
*/
changeUserName(name) {
this.userName = name;
}
},{
changeUserName: action,
changeUserAge: action
})
const App = observer(class App extends Component {
render() {
console.log('app render',toJS(myStore))
return (
<View style={styles.container}>
<View>
<AppUserNameItem data={myStore.userName} store={myStore}/>
<AppUserAgeItem data={myStore.userAge} store={myStore}/>
</View>
</View>
);
}
}
const AppUserAgeItem = observer(class AppUserAgeItem extends Component {
render() {
console.log('AppUserAgeItem render')
return (
<View style={{flexDirection: "row", marginTop: 20}}>
<Text style={{width: 100}}>你的年龄:</Text>
<TextInput value={String(this.props.data)} onChangeText={(value)=>{
// 调用方法直接修改姓名
this.props.store.changeUserAge(value);
}}/>
</View>
);
}
})
export default AppUserAgeItem
const AppUserNameItem = observer(class AppUserNameItem extends Component {
render() {
console.log('AppUserNameItem render')
return (
<View style={{flexDirection: "row", marginTop: 20}}>
<Text style={{width: 100}}>你的名字:</Text>
<TextInput value={String(this.props.data)} onChangeText={(value)=>{
// 调用方法直接修改姓名
this.props.store.changeUserName(value);
}}/>
</View>
);
}
})
export default AppUserNameItem
程序刚运行完毕
修改年龄(只走了AppUserAgeItem
的 render
方法)
修改姓名(只走了AppUserNameItem
的 render
方法)
所以喽~