gpt4 book ai didi

javascript - react native : cant add props to component

转载 作者:行者123 更新时间:2023-12-03 03:24:34 24 4
gpt4 key购买 nike

我正在开发简单的程序。我有 List.js 和 Detail.js,我想使用 Props 在 Detail.js 中获取 List.js 状态,但不起作用(props 不返回任何内容)。我试过this但仍然不工作。这就是我到目前为止所做的:

列表.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>
);
}

详细信息.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>;
}
}

<Text>{this.state.id}</Text>;没有显示任何内容

最佳答案

您需要更改此设置,

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');
});
}

并且您需要在详细信息组件上获取新的 Prop 并更新状态。 Why you shouldn't modify state directly 有一个非常好的答案

componentWillReceiveProps(nextProps) {
this.setState({ id: nextProps.data });
}

关于javascript - react native : cant add props to component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46389012/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com