React Native - Trouble passing parent#39;s state to child(React Native - 将父母的状态传递给孩子的麻烦)
问题描述
React 新手在从父组件(本例中为 App
)传递状态和函数以及从子组件(本例中为 Main
)访问时遇到一些问题.我确定这是一两个非常简单的错误,我在哪里被绊倒了?
a React newbie having some issues passing down states and functions from Parent Component (App
in this case) and accessing from Child Components (Main
in this case). I'm sure it's one or two really simple mistakes, where am I getting tripped up?
这是项目结构:
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}/>;
}
}
我得到的错误是 -- 有什么想法吗?提前致谢!
Error I'm getting is -- any ideas? Thanks in advance!
推荐答案
1-
这是不对的
<Card ... props should be here!!--- >
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>
正确答案是:
<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>
错误的意思是Card的孩子应该是一个对象而不是.....
The meaning of the error is that the child of Card is expected to be an object and not .....
2-
this.updateArr = this.updateArr.bind(this);
不是必需的,因为 updateArr = () =>;...
是用 es6 编写的
this.updateArr = this.updateArr.bind(this);
is not necessary since updateArr = () => ...
is written in es6
这篇关于React Native - 将父母的状态传递给孩子的麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:React Native - 将父母的状态传递给孩子的麻烦
基础教程推荐
- Chart.js 在线性图表上拖动点 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01