【问题标题】:How to pass props to React Picker如何将道具传递给 React Picker
【发布时间】:2019-10-25 17:18:18
【问题描述】:

我有一个来自react-native-picker-select 的选择器。我还有一个按钮,如果我按下它,我想将道具传递给选择器并将其显示为标签。

我尝试从按钮设置callback 函数,将道具传递给选择器,并将标签设置为道具。我可以看到正在传递的道具,但选择器没有更新。

Score.js

<View style={styles.button}>
  <TouchableOpacity
         style={styles.scoreButton}
         onPress={() => this.props.pressMe()}>
         <Text style={{ color: 'white' }}>Press</Text>
  </TouchableOpacity>
</View>

Main.js

pressMe = () => {
    if (this.state.level== 1) {
      this.setState({ scoreInput: 100 });
    }
  };

<Deadlift
   scoreInput={this.state.scoreInput}/>

<View style={styles.scoreContainer}>
   <Score
      pressMe={this.pressMe} />
</View>

Deadlift.js

 var picker = (<Picker
          {...this.props}
          style={pickerSelectStyles}
          placeholder={{
            label: 'Weight',
            value: null,
          }}
          items={this.state.items}
          onValueChange={value => {
            onDLHandler(value, this.getScore(value));
          }}
          value={this.props.scoreInput} <- outside of picker shows this is 
                          logged as 100 but value is not being updated on picker
        />)

<View>{picker}</View>

【问题讨论】:

  • 你的 scoreOutput 组件在哪里
  • 刚刚更新了
  • 在 main.js 中将 pressMe={this.pressMe} 更改为 pressMe={(value) =&gt; this.pressMe(value)} 并删除 {...this.props} 并在 scoreOutput.js 中添加 onValueChange={(value) =&gt; this.props. pressMe(value)}
  • 那行不通。另外,我没有将 pressMe 直接传递给 scoreOutput。我将它传递给 main.js,然后将 scoreInput 道具传递给 scoreOutput。
  • @fosho 您的 scoreOutput 组件在哪里主要或某处使用?我只看到 scoreInput

标签: reactjs react-native


【解决方案1】:

根据documentation的“价值”道具

将尝试通过以下方式从 items 数组中找到匹配的项目 检查每个项目的 value 属性。如果找到,它将更新 组件以将该项目显示为选中状态。如果找不到该值,则 将默认为第一项。

选择器在 items 数组中找不到对象“{ scoreInput: 100 }”,因此选择器不会更新。如果要更新选择器,还必须添加 items 数组

【讨论】:

  • 这是我在文档中发现的。必须将项目数组传递到我设置状态的位置,然后将状态推送到数组,然后将项目数组传回选择器。
【解决方案2】:

正如文档所述,项目应该是具有标签和值键的对象数组,而不仅仅是值数组

https://github.com/lawnstarter/react-native-picker-select/blob/master/README.md#props

【讨论】:

  • 谢谢,我就是这样用的。我的选择器工作正常。只是不是我在原始问题中的描述。
猜你喜欢
  • 2018-08-01
  • 2020-12-19
  • 2020-06-13
  • 2014-03-12
  • 1970-01-01
  • 2018-04-25
  • 2018-08-25
  • 2015-09-21
  • 1970-01-01
相关资源
最近更新 更多