React js传递一个函数this.state上下文 [英] React js pass a function this.state context
本文介绍了React js传递一个函数this.state上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在文件中具有以下功能:
I have the following function in a file:
helpers.js:
helpers.js:
export const returnStateElement = (...elements) => {
console.log("returnStateElement",this,elements)
const copy = Object.assign({}, this);
return elements.reduce((obj, key) => ({ ...obj, [key]: copy[key] }), {});
};
index.js:
import { validateEmail, returnStateElement } from '../../helpers'
...
constructor(props) {
super(props);
this.state = {
email: "site@host.com",
};
}
...
handleSubmit = () => {
const dataSender = this.state.returnStateElement("email");
console.log("handleSubmit",dataSender)
}
我想通过做这样的事情来做到这一点:
I would like to do that by doing such a thing:
this.state.returnStateElement("email")
作为此状态传递,this.state是我将返回包含在函数参数中的值.
passed as this state, this.state is I would return the values which are contained as function arguments.
链接:代码沙盒
推荐答案
您需要将上下文绑定到该函数.这是一份工作点心,展示了您可能如何在构造函数中做到这一点
You need to bind the context to the function. Here is a working snack showing how you might do that in the constructor
https://snack.expo.io/Sy8J3fyGL
和代码
import * as React from 'react';
import {Button, TouchableOpacity, Text, View, StyleSheet } from 'react-native';
const returnStateElement = (currentState, ...elements) => {
const copy = Object.assign({}, currentState);
return elements.reduce((obj, key) => ({ ...obj, [key]: copy[key] }), {});
};
export default class App extends React.Component {
constructor(props) {
super(props)
this.state = {
email: 'test@test.com'
}
this.returnStateElement = (...elements) => returnStateElement(this.state, ...elements);
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity onPress={() => alert(JSON.stringify(this.returnStateElement('email', 'pass')))}>
<Text style={styles.paragraph}>Press here</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#ecf0f1',
padding: 8,
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
});
这篇关于React js传递一个函数this.state上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文