react普通属性如何存储
在 React 中存储普通属性
React 组件中的普通属性通常通过组件的 props 或内部状态(state)来存储和管理。以下是具体方法:
使用 Props 传递属性
Props 是父组件向子组件传递数据的方式,子组件通过 this.props(类组件)或直接通过参数(函数组件)访问这些属性。
类组件示例:
class ChildComponent extends React.Component {
render() {
return <div>{this.props.message}</div>;
}
}
class ParentComponent extends React.Component {
render() {
return <ChildComponent message="Hello from parent" />;
}
}
函数组件示例:
function ChildComponent({ message }) {
return <div>{message}</div>;
}
function ParentComponent() {
return <ChildComponent message="Hello from parent" />;
}
使用 State 管理内部属性
State 用于存储组件内部可变的数据,通过 this.state(类组件)或 useState Hook(函数组件)实现。
类组件示例:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
render() {
return <div>{this.state.count}</div>;
}
}
函数组件示例:
function MyComponent() {
const [count, setCount] = React.useState(0);
return <div>{count}</div>;
}
直接存储为实例属性
对于不需要触发渲染的普通属性,可以存储在组件实例上(类组件)或通过 useRef Hook(函数组件)。
类组件示例:
class MyComponent extends React.Component {
timerId = null;
componentDidMount() {
this.timerId = setInterval(() => {}, 1000);
}
componentWillUnmount() {
clearInterval(this.timerId);
}
}
函数组件示例:
function MyComponent() {
const timerId = React.useRef(null);
React.useEffect(() => {
timerId.current = setInterval(() => {}, 1000);
return () => clearInterval(timerId.current);
}, []);
}
选择存储方式的依据
- Props:适用于父组件向子组件传递数据。
- State:适用于组件内部需要触发重新渲染的可变数据。
- 实例属性/Ref:适用于不需要触发渲染的辅助数据或 DOM 引用。






