react箭头函数如何传参
箭头函数传参基础语法
箭头函数通过括号内的参数列表接收参数,单参数时可省略括号。例如:
const greet = name => `Hello, ${name}!`;
console.loggreet("Alice")); // 输出: Hello, Alice!
多参数时必须使用括号:
const sum = (a, b) => a + b;
console.logsum(2, 3)); // 输出: 5
默认参数设置
箭头函数支持ES6默认参数语法:
const multiply = (x, y = 1) => x * y;
console.logmultiply(5)); // 输出: 5 (y默认为1)
console.logmultiply(5, 2)); // 输出: 10
对象解构传参
可直接在参数中解构对象:
const userInfo = ({ name, age }) => `${name} is ${age} years old`;
console.loguserInfo({ name: "Bob", age: 30 })); // 输出: Bob is 30 years old
剩余参数处理
使用...rest语法接收不定数量参数:
const average = (...nums) => nums.reduce((a, b) => a + b) / nums.length;
console.logaverage(1, 2, 3, 4)); // 输出: 2.5
React组件中的props传递
在React组件中通常通过props对象传递参数:
const Button = ({ onClick, children }) => (
<button onClick={onClick}>{children}</button>
);
// 使用时
<Button onClick={() => console.log("Clicked")}>Click Me</Button>
高阶组件参数传递
箭头函数可方便地用于高阶组件:
const withLoading = (Component) => ({ isLoading, ...props }) =>
isLoading ? <div>Loading...</div> : <Component {...props} />;






