我们先来看一个处理点击事件的例子。
import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
const App = () => {
const [count, setCount] = useState(0);
const handalClick = () => {
setCount(count + 1)
};
return (
<div>
<p>You clicked {count} times</p>
<button onClick={handalClick}>
+ 1
</button>
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
容易理解,这是一个每点击一次就会让 count
变量加1的函数,如果我们想让函数带上参数,用参数来决定增加的数量,那该怎么做呢。
我们先这样尝试一下。
const App = () => {
const [count, setCount] = useState(0);
const handalClick = (num) => {
setCount(count + num)
};
return (
<div>
<p>You clicked {count} times</p>
<button onClick={handalClick(10)}>
+ 10
</button>
</div>
);
}
如果这样做,React 会给我们如下报错信息,显示会无限循环了:
Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
正确的做法应当是让函数返回另一个函数:
const App = () => {
const [count, setCount] = useState(0);
const handalClick = (num) => () => {
setCount(count + num)
};
return (
<div>
<p>You clicked {count} times</p>
<button onClick={handalClick(10)}>
+ 10
</button>
</div>
);
}
将事件处理传递到子组件
const Button = (props) => (
<button onClick={props.handleClick}>
{props.text}
</button>
)
const App = () => {
const [count, setCount] = useState(0);
const setToCount = (newCount) => {
setCount(newCount)
}
return (
<div>
<p>You clicked {count} times</p>
<Button handleClick={() => setToCount(count + 10)} text='+ 10' />
<Button handleClick={() => setToCount(count + 100)} text='+ 100' />
</div>
);
}
网页效果
注意要使用正确的名称,来确保 props
组件获得正确的属性。
网友评论