【问题标题】:Export functions out of react native components从反应原生组件中导出函数
【发布时间】:2017-11-23 19:46:40
【问题描述】:

我只想将函数导出到 actions.js 文件,但我无法开始工作。 这是工作基地:

export default class HomeScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false
    }
  }

  onOpen = () => {
    this.setState({visible:true});
    console.log(this.state.visible);
  }

  render() {
    return (
      <View style={styles.container}>
        <Button onPress={()=>{this.onOpen();}}>More</Button>
      </View>
    );
  }
}

现在我尝试了这个,当我按下按钮时出现错误:

错误:

Unhandled JS Exception: _this.setState is not a function. (In '_this.setState({ visible: true })', '_this.setState' is undefined)

代码:

let onOpen = () => {
  this.setState({visible:true});
  console.log(this.state.visible);
}

export default class HomeScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false
    }
    this.onOpen = onOpen.bind(this);
  }

  render() {
    return (
      <View style={styles.container}>
        <Button onPress={()=>{this.onOpen();}}>More</Button>
      </View>
    );
  }
}

【问题讨论】:

  • 您能否更具体地说明您要导出的功能?
  • 我明白你的意思,但你应该阅读更多关于类和 OOP 模式以及如何使用 this 的内容

标签: reactjs react-native


【解决方案1】:

您不能在类 Component 之外使用“this”关键字。您不能从类外部更改组件的状态。

更多细节在这里: Change state Outside Component

另外,如果你想在一个类之外改变组件的状态,使用redux state。

Redux JS

【讨论】:

    【解决方案2】:

    您的代码的问题是您在类之外定义了onOpen,并且您想访问组件的setState 函数。我不知道为什么要这样做,因为onOpen 属于类。但如果你想把这个放在课外。您可以通过以下方式做到这一点:

    let onOpen = ({setState}) => {
      //retrieve setState here
      setState({visible:true});
    }
    
    export default class HomeScreen extends Component {
      constructor(props) {
        super(props);
        this.state = {
          visible: false
        }
        // You don't have to do this if onOpen is not in your class
        //this.onOpen = onOpen.bind(this);
      }
    
      render() {
        //send this.setState to onOpen
        const that = this;
    
        return (
          <View style={styles.container}>
            <Button onPress={()=>{onOpen({setState: that.setState});}}>More</Button>
          </View>
        );
      }
    }
    

    【讨论】:

    • 感谢您的回复,但它不起作用:我收到错误:undefined is not an object (evalating 'this.updater') - 我的问题的原因是我有这么多状态和我的类中的函数,我失去了概述并想要重构它。
    • 这不是重构类的正确方法。而是在您的应用中使用 redux 并制作更小的 React 组件。
    • 好的,谢谢,你说得对,我会用 redux 做不同的事情!但您的代码仍然有效。也许就像 Manoj Prabhakar 说的那样,改变外面的状态是不可能的
    • 显然不可能。这就是为什么你应该学习和学习如何在面向对象编程中思考。如果某物属于类。它应该在一个类中编写和访问,除非你正在做一些继承或抽象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 2019-01-22
    • 2019-03-03
    • 1970-01-01
    • 2019-06-10
    • 1970-01-01
    相关资源
    最近更新 更多