【问题标题】:React js pass a function this.state contextReact js 传递一个函数 this.state 上下文
【发布时间】:2020-01-29 13:57:56
【问题描述】:

我在一个文件中有以下函数:

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)
}

我想通过做这样的事情来做到这一点:

this.state.returnStateElement("email")

作为这个状态传递,this.state 是我将返回作为函数参数包含的值。

链接:codesandbox

【问题讨论】:

  • this.state["email"]
  • 试试这个:this.setState({ returnStateElement: returnStateElement.bind(this.state) });。把它放在this.state = {...}的下面
  • 不起作用..

标签: javascript reactjs function


【解决方案1】:

您需要将上下文绑定到函数。这是一个工作零食,展示了如何在构造函数中执行此操作

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',
  },
});

【讨论】:

    猜你喜欢
    • 2021-02-23
    • 2021-09-19
    • 1970-01-01
    • 2019-10-18
    • 2018-05-12
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多