【发布时间】:2019-07-18 08:01:36
【问题描述】:
我正在使用react-native 构建应用程序。我有 3 个组件,即 Ind.js、Buttons.js、Rain.js。我需要在Rain 中选择一个选项并将其保存为Ind 的状态以供进一步处理。因为Rain 组件与Ind 没有直接关系,而是通过Buttons 中的navigation route 连接。
我正在使用react-navigation。
为此,我在Ind 中创建了一个函数onSelect(),它执行setState,并通过道具将其传递给Buttons,然后再次传递给Rain,然后我执行了该函数,问题在于函数正在被调用,但没有传递任何参数,即 console.logs null 然后 undefined。
我已尝试将console.log 传递给Ind 的参数。
Ind.js
export default class Ind extends Component {
constructor(){
super();
this.state = { report: null}
}
onSelect = (newreport) => {
this.setState({
report: newreport
})
console.log("Parameter: ", newreport)
console.log("State: ", this.state.report)
}
render(){
return(
<Buttons selectReport={() => this.onSelect()}
)
}
}
Buttons.js
export default class Buttons extends Component{
constructor(props){
super(props);
}
render(){
return(
<TouchableOpacity
onPress={() => {this.props.navigation.navigate('Rain',{
selectReport: this.props.selectReport });
}}>
<Text style={styles.text}>Rain</Text>
</TouchableOpacity>
)
}
}
Rain.js
export default class Rain extends Component{
constructor(props){
super(props);
this.state = {
selection: "Test"
}
this.selectOption = this.selectOption.bind(this);
}
selectOption = () => {
this.props.navigation.state.params.selectReport(this.state.selection)
}
}
console log 首先返回 Parameter: undefined State: null,这是可以理解的,因为没有点击任何内容,但点击后会显示
Parameter: undefined State: undefined。
怎么了?我是初学者,绑定或发送道具有什么问题吗?
请解释一下。
【问题讨论】:
标签: javascript react-native state setstate react-props