【发布时间】:2018-08-04 19:53:48
【问题描述】:
一个 React 新手在从父组件(本例中为 App)传递状态和函数以及从子组件(本例中为 Main)访问时遇到一些问题。我确定这是一两个非常简单的错误,我在哪里被绊倒了?
这是项目结构:
App
|__ Rootstack
|
|__Favorites
|__Main
这是精简后的代码:
class Main extends React.Component {
render() {
return (
<View>
<Text>{this.props.favoritesList.length}</Text>
<Card>
onSwiped={() => {this.props.updateArray}} //the idea being that on a swipe, updateArray would add 1 to the 'favoriteList' in the parents state, and the favoritesList.length would update by +1.
</Card>
</View>
);
}
}
class Favorites extends React.Component {
....
}
const RootStack = StackNavigator(
{
Main: {
screen: Main},
Favorites: {
screen: Favorites}
},
{
initialRouteName: 'Main'
}
);
export default class App extends Component<{}> {
constructor(props) {
super(props);
this.state = {
favoritesList: []
};
this.updateArr = this.updateArr.bind(this); //don't know if this is necessary?
}
updateArr=()=>{this.setState({ favoritesList:
[...this.state.favoritesList, 'new value']})};
render() {
return <RootStack {...this.state} updateArray={this.updateArr}/>;
}
}
【问题讨论】:
-
您正在尝试通过导航器发送道具并通过您的组件访问它。你不能通过这种方式通过导航器发送道具。看看this,它可能会对你有所帮助。
-
首先不需要绑定箭头函数,其次您将道具传递给无状态组件,并且导航器也无法直接接收道具。
标签: javascript reactjs react-native components parent-child