我有一个下拉菜单组件(名称:JDrop):
import React, { Component } from 'react';
import { View,Picker,Image } from 'react-native';
export default class JDrop extends Component {
constructor(props,state) {
super(props)
this.state = {
selectedValue:'',
}
}
render() {
const {items,sizeW,bColor} = this.props;
return (
<View style={{flexDirection: 'row',height: 35, width: sizeW, alignItems: 'center',backgroundColor:bColor}}>
<View>
<Image style={{width:20,height:10, margin:5}} source={require('../../assets/Images/arrowb.png')}/>
</View>
<View >
<Picker
mode='dropdown'
style={{height: 35, width: sizeW,backgroundColor:bColor}}
selectedValue={this.state.selectedValue}
onValueChange={(itemValue, itemIndex) => this.setState({selectedValue: itemValue})}
prompt='Select...'
>
{
items.map( (item,ind) => (
<Picker.Item label={item.name} value={item.value} key={ind} />
))
}
</Picker>
</View>
</View>
)
}
}
我在App.js中使用它,例如:
<JDrop items={this.state.priority} sizeW={200} bColor={'blue'} ></JDrop>
如何从 App.js 中的 JDrop 获得 selectedValue ?
答案 0 :(得分:2)
有几种方法,但是最简单的方法是将更改处理程序从父级传递给子级,以便可以传达子级中的更改。像这样:
class App extends React.Component {
onChangeJDrop = (val) => {
console.log(val)
}
render() {
return (
<JDrop onChange={this.onChangeJDrop} items={this.state.priority} sizeW={200} bColor={'blue'} ></JDrop>
)
}
}
class JDrop extends React.Component {
onValueChange = (itemValue, itemIndex) => {
this.setState({selectedValue: itemValue})
this.props.onChange(itemValue)
}
render() {
return (
<Picker onValueChange={this.onValueChange} />
)
}
}
答案 1 :(得分:0)
您需要将回调传递到您的JDrop组件(在下面命名为onSelect):
<JDrop onSelect={this.onSelect} items={this.state.priority} sizeW={200} bColor={'blue'} ></JDrop>
然后在您的JDrop组件中:
onValueChange={(itemValue, itemIndex) => {
this.setState({selectedValue: itemValue})
this.props.onSelect(itemValue)
} }