感觉我的问题很简单,但我不明白为什么它不起作用。
为什么我要尝试做一些基本的事情——我将一个函数从父级传递给子级,它应该将父级的“测试”值的值(这只是一个概念证明)增加 1。问题调用父函数时发生。我收到“无法读取未定义的属性测试”。在调试器中,this.props 也是未定义的,所以 this.props.test 将是不足为奇的。我错过了什么?
家长:
export default class GameList extends Component {
constructor({ navigation }) {
super();
this.state = {
test: 0,
}
};
updateState() {
this.setState({
test: this.state.test++,
});
}
render() {
return (
<View style={styles.background}>
<Header updateState={this.updateState} />
</View >
)
}
}
child :
import React, { Component } from 'react';
import { View, TextInput } from 'react-native';
import styles from './styles';
class Header extends Component {
render() {
return (
<View style={styles.container}>
<TextInput
style={styles.input}
placeholder="Search..."
onChangeText={(text) => {
this.props.updateState();
}}
/>
</View>
);
}
filterRows(searchText, dataSet) {
return dataSet.filter((record) => record.title.includes(searchText));
}
}
export default Header;
最佳答案
有两个问题:
- 在您的构造函数中绑定(bind)该方法,为其提供正确的上下文。关于为什么这是必要的更多信息在 React documentation under Handling Events 中。 .
- 不要在状态属性上使用
++
,因为它会修改原始状态,并且在检查是否重新渲染时可能会破坏任何比较(即this.state.test === newState.test
? 是的,因为原来的已经改了)。在 React documentation under Component 下有更多信息,请注意他们如何使用quantity: state.quantity + 1
而不是quantity: state.quantity++
所以你得到:
export default class GameList extends Component {
constructor({ navigation }) {
super();
this.state = {
test: 0,
}
this.updateState = this.updateState.bind(this); // Bind to the correct context
};
updateState() {
this.setState({
test: this.state.test + 1, // Do not mutate the original state
});
}
render() {
return (
<View style={styles.background}>
<Header updateState={this.updateState} />
</View >
)
}
}
关于javascript - react 子 JSX 元素不从父级继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43708996/