[英]how bind correctly in react-native?
I'm try to update the state from a function, but I don't find the correct form to bind the scope.我试图从函数更新状态,但我没有找到绑定作用域的正确形式。 My code (I am working with native-base components):
我的代码(我正在使用本机基础组件):
export default class MenuScreen extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
_renderRow() {
return (
<ListItem avatar onPress={() =>
ActionSheet.show(
{options: BUTTONS
}, buttonIndex => { setState({ clicked: BUTTONS[buttonIndex]})}
)}
>
</ListItem>
);
}
render() {
return (
<SectionList
sections={[...]}
renderItem={this._renderRow}
/>
);
}
First option, bind it in constructor第一个选项,在构造函数中绑定它
Example例子
constructor(props) {
super(props);
this.state = {};
this._renderRow = this._renderRow.bind(this);
}
Second option, bind it inline第二个选项,内联绑定
Example例子
<SectionList
sections={[...]}
renderItem={this._renderRow.bind(this)}
/>
Third option, use arrow functions第三个选项,使用箭头函数
Example例子
renderRow = () => {
return (
<ListItem avatar onPress={() =>
ActionSheet.show(
{options: BUTTONS
}, buttonIndex => { this.setState({ clicked: BUTTONS[buttonIndex]})}
)}
>
</ListItem>
);
}
My recommendation would be to read this: https://medium.freecodecamp.org/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56 Helps a lot with understanding binding options you have and why one or other might be better in your case.我的建议是阅读以下内容: https: //medium.freecodecamp.org/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56 对理解您拥有的绑定选项以及为什么其中一个或其他选项可能有很大帮助在你的情况下会更好。
I suggest to go with binding in constructor
:我建议在
constructor
使用绑定:
export default class MenuScreen extends React.Component {
constructor(props) {
super(props);
this.state = {};
this.handleChange = this.handlePress.bind(this);
}
...
self mental note, "Bind is dummy if I not use the context of the function"自我心理笔记,“如果我不使用函数的上下文,则绑定是虚拟的”
export default class MenuScreen extends React.Component {
constructor(props) {
super(props);
this.state = {};
**this._renderRow = this._renderRow.bind(this);**
}
_renderRow() {
return (
<ListItem avatar onPress={() =>
ActionSheet.show(
{options: BUTTONS
}, buttonIndex => { **this.**setState({ clicked: BUTTONS[buttonIndex]})}
)}
>
</ListItem>
);
}
render() {
return (
<SectionList
sections={[...]}
renderItem={this._renderRow}
/>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.