React
React组件中的props
- 是一个对象,其包含了所有传给组件的属性
- 函数式组件中在函数中使用参数接收
- props本质上是一个常量,而不是state或ref
- 组件内部不能直接修改props
- 每次父组件渲染,子组件会收到新的props常量值
- 尽管props是常量,但可以被useEffect监听到变化,见useEffect
- props变化会触发组件重新渲染,创建一个新的props常量
示例
// 类组件中使用props
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
// 函数式组件中使用props
const Greeting = (props) => {
return <h1>Hello, {props.name}</h1>;
}
// 使用解构函数参数简化函数式组件中的props访问
const Greeting = ({ name }) => {
return <h1>Hello, {name}</h1>;
}
// 通过useEffect监听props变化
const Greeting = ({ name }) => {
useEffect(() => {
console.log(`Name changed to: ${name}`);
// 可以执行其他依赖于name的副作用操作
}, [name]); // 监听name prop变化
return <h1>Hello, {name}</h1>;
}