简体   繁体   English

如何在 React 中编写由 useCallback 优化的 onClick(带参数)?

[英]how to write onClick (with arguments) optimized by useCallback in React?

I need to implement a long list, each item in the long list will trigger a new function when onClick, because this function is unchanged every time it is rendered, so I want to use useCallback to optimize it, this returned function Fn needs to pass in parameters, so should I use bind to pass parameters in onClick? I need to implement a long list, each item in the long list will trigger a new function when onClick, because this function is unchanged every time it is rendered, so I want to use useCallback to optimize it, this returned function Fn needs to pass在参数中,那么我应该使用bind来传递onClick中的参数吗?

    const func = useCallback((num) => setIndex(num), [])
    // myComponent
    <TableItem onClick = { func.bind(null, index) } />

This is my first question, please forgive me if something is wrong,Thanks.这是我的第一个问题,如有错误请见谅,谢谢。

If you pass a callback to multiple components then you can use useCallback in the following way:如果将回调传递给多个组件,则可以通过以下方式使用 useCallback:

 //make Counter a pure component (only re renders if something changed) const Counter = React.memo(function Counter({ counter, up, index, }) { // ok to do onClick={new=>'function'} because we do not pass // onClick to sub components unless counter changes console.log('rendering index:', index); return ( <button onClick={() => up(index)}>{counter}</button> ); }); const App = () => { //fixed amount of items that does not re order so can use index // in key, do not use index as key when you don't have fixed // amount of items or re order the list. const [counters, setCounters] = React.useState([0, 0]); const up = React.useCallback( (index) => //pass callback to setCounters so counters is not // a dependency of useCallback setCounters((counters) => counters.map((counter, i) => i === index? counter + 1: counter ) ), []//empty dependency, only created when App mounts ); return ( <ul> {counters.map((counter, index) => ( <Counter up={up} counter={counter} key={index} index={index} /> ))} </ul> ); }; ReactDOM.render(<App />, document.getElementById('root'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="root"></div>

You need to set the second param in useCallback, this will prevent multiple renders.您需要在 useCallback 中设置第二个参数,这将防止多次渲染。

ie, if you want to set it just in when the component starts you can set即,如果你想在组件启动时设置它,你可以设置

useCallback((num => setIndex(num)), [])

Note that [], it means it will only render at the beginning, if you want to update it when any variable changes, you can set [variablename, ...]注意[],表示它只会在开头渲染,如果你想在任何变量发生变化时更新它,你可以设置[variablename, ...]

Also, I think you don't need the func.bind, you can set only另外,我认为您不需要func.bind,您只能设置

<Component onClick={func}/>

Edit: I misunderstood this question.编辑:我误解了这个问题。

If you want to send a param in the onClick you can set it like this如果要在 onClick 中发送参数,可以这样设置

const func = useCallback((num => setIndex(num)), [])
<Component onClick={()=>func(yourParam)}/>

With this way your onClick will always use the function, but it allows a param that you can set anywhere通过这种方式,您的 onClick 将始终使用 function,但它允许您可以在任何地方设置的参数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM