【问题标题】:react-native : cant add props to componentreact-native:无法向组件添加道具
【发布时间】:2017-09-24 10:22:55
【问题描述】:

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

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

&lt;Text&gt;{this.state.id}&lt;/Text&gt;; 什么都不显示

【问题讨论】:

    标签: javascript android react-native


    【解决方案1】:

    你需要改变它,

    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 组件上获取新的 prop 并更新状态。 Why you shouldn't modify state directly 有一个非常好的答案

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

    【讨论】:

    • 谢谢这是一个很好的答案,但&lt;Text&gt;{this.state.id}&lt;/Text&gt; 仍然没有显示任何内容,似乎来自 List.js 的道具没有传递给 Detail 组件。因为当我尝试this.setState({ id: "Test" }); 时,状态没有改变@bennygenel
    • 可能是视觉问题。请在componentWillReceiveProps 中输入console.log(nextProps.id),看看是否能看到正确的id。
    • console.log(nextProps.id) 打印未定义,似乎问题出在 List.js 上时将道具传递给 Detail,但我不知道为什么 @bennygenel
    • 我明白了,先生,我将 nextProps.id 更改为 nextprops.data,谢谢! @bennygenel
    • 我只是在写那个
    猜你喜欢
    • 1970-01-01
    • 2021-04-21
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    • 2017-05-10
    • 2018-05-23
    • 2019-02-27
    • 1970-01-01
    相关资源
    最近更新 更多