react-native:无法向组件添加道具 [英] react-native : cant add props to component
本文介绍了react-native:无法向组件添加道具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在开发简单的程序.我有 List.js 和 Detail.js,我想使用 Props 在 Detail.js 中获取 List.js 状态但不起作用(props 不返回任何内容).我尝试了这个,但仍然无法正常工作.这是我到目前为止所做的:
im working on simple program. I have List.js and Detail.js and i want to get List.js state in Detail.js using Props but not working (props returns nothing). I tried this but still not working. This is what i did so far :
List.js:
import {Detail} from './Detail';
.
.
.
.
GetItem (nama,id) {
this.setState({id: id});
return this.props.navigation.navigate('detail');
}
.
.
.
.
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return (
<View style={styles.MainContainer}>
<View><TextInput style={{height: 40,width: 300, marginTop:10}}
onChangeText={this.onKeyChanges.bind(this)}
/>
</View>
<View><ListView
dataSource={this.state.dataSource}
renderSeparator= {this.ListViewItemSeparator}
renderRow={(rowData) => <Text style={styles.rowViewContainer}
onPress={this.GetItem.bind(this, rowData.nama,rowData.id)} >{rowData.nama}</Text>}
/>
</View>
<Detail data={this.state.id}/>
</View>
);
}
Detail.js
export class Detail extends React.Component
{
constructor(props)
{
super(props);
this.state = {
id: props.data
}
}
componentWillUpdate(nextProps, nextState) {
nextState.id = nextProps.data;
}
render() {
return <Text>{this.state.id}</Text>;
}
}
什么都没显示
the <Text>{this.state.id}</Text>;
shows nothing
推荐答案
你需要改变这个,
GetItem (nama,id) {
this.setState({id: id});
return this.props.navigation.navigate('detail');
}
到这里
// setState is asynchronous
GetItem (nama,id) {
this.setState({id: id}, () => {
this.props.navigation.navigate('detail');
});
}
并且您需要在 Details 组件上获取新道具并更新状态.为什么不应该直接修改状态
And you need to get new prop on Details component and update the state. There is a really good answer for Why you shouldn't modify state directly
componentWillReceiveProps(nextProps) {
this.setState({ id: nextProps.data });
}
这篇关于react-native:无法向组件添加道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文