javascript - 如何在不绑定 React-Native 的情况下将参数传递给函数
问题描述
所以,我读过做这样的事情
<SomeButton onPress={() => { this.someFunction(args)}} />
不好,因为它正在为每个渲染周期创建一个新的函数实例。
但是我如何在 React-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>
推荐阅读
- python - 如何在 Pandas 的两个 Dataframe 上访问每个相同的索引单元格?
- postgresql - 将字符串日期(DD-MM-YYYY)与当前日期 postgress 进行比较
- php - 舍入/限制 ms-duration (DateTime::diff) 到一位
- python - Astropy transform_to 忽略春分
- c++ - “转换表达式”,我们必须将给定的中缀表达式转换为后缀表达式
- compression - 棋位压缩
- pdf - 在 PDF 中创建指向页面内部的超链接
- reactjs - 如何使用查询字符串在 Next.js 中创建 api 端点
- r - 将列名合并到R中的字符串中
- r - 有人可以帮我解决在 R 中估计 VAR 模型时遇到的这个错误吗?