首页 > 解决方案 > 如何在不绑定 React-Native 的情况下将参数传递给函数

问题描述

所以,我读过做这样的事情

<SomeButton onPress={() => { this.someFunction(args)}} />

不好,因为它正在为每个渲染周期创建一个新的函数实例。

但是我如何在 React-Native 中传递参数呢?

标签: javascriptreactjsreact-native

解决方案


Creating a new inline function is fine in many cases, but if you have a lot of SomeButton components it might be worth passing the args as props to the component and use that as arguments in the component's onPress instead.

Example

class SomeButton extends React.Component {
  handleClick = () => {
    const { onClick, someProp } = this.props;
    onClick(someProp);
  };

  render() {
    return <button onClick={this.handleClick}>Click me</button>;
  }
}

class App extends React.Component {
  handleClick = arg => {
    console.log(arg);
  };

  render() {
    return <SomeButton onClick={this.handleClick} someProp="foo" />;
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/react@16.4.1/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16.4.1/umd/react-dom.production.min.js"></script>

<div id="root"></div>


推荐阅读