Reactjs 无法在父组件中设置状态
我无法从子组件调用父组件上的setState 我试图通过在父组件中绑定一个函数并在该函数中调用setState来解决这个问题。我在子组件的props中传递了该函数,但它仍然无法找到父组件setState函数Reactjs 无法在父组件中设置状态,reactjs,react-native,graphql,Reactjs,React Native,Graphql,我无法从子组件调用父组件上的setState 我试图通过在父组件中绑定一个函数并在该函数中调用setState来解决这个问题。我在子组件的props中传递了该函数,但它仍然无法找到父组件setState函数 const CrewsAdapter = props => { if(props.data.loading) { return <View><Text>Loading crews</Text></View> } if(
const CrewsAdapter = props => {
if(props.data.loading) {
return <View><Text>Loading crews</Text></View>
}
if(props.data.getAllCrews) {
crewsNames= props.data.getAllCrews.map(crew => ({"value": crew.crewName}));
return (
<View style={{ flexDirection: 'column', alignItems: 'center', backgroundColor: '#ffffff' }}>
<View style={[styles.container, { flex: 0.25 }]}>
<Text style={styles.headerText}>Crews</Text>
</View>
<View style={{ flexDirection: 'row' }}>
<View style={{ flex: 0.9 }}>
<Dropdown label="Crews List"
data={crewsNames}
onChangeText = {(value) => {this.props.stateHandler(value)}}
/>
</View>
</View>
<View style={{ flexDirection: 'row' }}>
<Crew/>
</View>
</View>
);
}
return <View><Text>No data</Text></View>
};
export default class CrewsScreen extends Component {
constructor(props) {
super(props);
this.stateHandler = this.stateHandler.bind(this);
this.state = {
crewName: '',
}
}
stateHandler(value){
this.setState({crewName: value});
}
render() {
const AllCrews = graphql(crewsList, {options: (props => ({}))})(CrewsAdapter);
return (
<SafeAreaView style={styles.screen}>
<ToolBar />
<AllCrews stateHandler = {this.stateHandler}/>
<CrewsListFooter navProps={{...this.props}}/>
</SafeAreaView>
);
}
}
const CrewsAdapter=props=>{
if(道具数据加载){
返回装载队
}
if(props.data.getAllCrews){
crewsNames=props.data.getAllCrews.map(crew=>({“value”:crew.crewName}));
返回(
船员
{this.props.stateHandler(value)}
/>
);
}
不返回任何数据
};
导出默认类CrewsScreen扩展组件{
建造师(道具){
超级(道具);
this.stateHandler=this.stateHandler.bind(this);
此.state={
crewName:“”,
}
}
stateHandler(值){
this.setState({crewName:value});
}
render(){
const allcrows=graphql(crewsList,{options:(props=>({}))})(CrewsAdapter);
返回(
);
}
}
当下拉列表更改时,我尝试设置状态
<Dropdown label="Crews List"
data={crewsNames}
onChangeText = {(value) => {this.props.stateHandler(value)}}
/>
{this.props.stateHandler(value)}
/>
但是我得到了一个错误:“undefined不是一个对象(计算_this.props.stateHandler)”
非常感谢您的帮助。请尝试onChangeText={(value)=>{props.stateHandler(value)}
您的子组件是一个无状态的功能组件,也就是一个函数,它以
props
作为参数。在这种情况下,您不能通过'this.props'访问props,因为它不是React.component
的实例。您只需通过props来访问它。[propName]
就像你是其他的道具一样-所以这个。道具是未定义的。回答正确!如果有redux,只需调用parents函数来设置状态