ReactJS 道具验证ReactJS 状态
ReactJS 道具(Props)
状态和道具之间的主要区别props是不可变的。这就是为什么容器组件应定义可以更新和更改的状态,而子组件应仅使用prop从状态传递数据的原因。
使用道具当我们需要在组件中使用不可变数据时,我们可以在main.js中的reactDOM.render()函数中添加道具,并在组件中使用它。
App.jsximport React from 'react';
class App extends React.Component {
render() {
return (
{this.props.headerProp}
{this.props.contentProp}
);
}
}main.jsimport React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(
export default App;这将产生以下结果。
默认道具您还可以直接在组件构造函数上设置默认属性值,而不是将它添加到 reactDom.render ()元素中。
App.jsximport React from 'react';
class App extends React.Component { render() {
return (
{this.props.headerProp}
{this.props.contentProp}
);
}
}
App.defaultProps = {
headerProp: "Header from props...",
contentProp:"Content from props..."
}
export default App;main.jsimport React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(
状态与道具以下示例显示了如何state在应用中进行合并和支持。我们在父组件中设置状态,然后使用props将其传递到组件树中。在render函数内部,我们正在设置headerProp并contentProp在子组件中使用。
App.jsximport React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
header: "Header from props...",
content: "Content from props..."
}
}
render() {
return (
);
}
}
class Header extends React.Component {
render() {
return (
{this.props.headerProp}
);
}
}
class Content extends React.Component {
render() {
return (
{this.props.contentProp}
);
}
}
export default App;main.jsimport React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(
ReactJS 道具验证ReactJS 状态