React SERIES V (react props)
Keywords:
React
React SERIES V (react props)
1, Using React Props
The main difference between state and props is that props is immutable, and state can be changed according to the interaction with users.
This is why some container components need to define state to update and modify data. Sub components can only pass data through props.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Use props</title>
<script src="https://cdn.bootcss.com/react/15.4.2/react.min.js"></script>
<script src="https://cdn.bootcss.com/react/15.4.2/react-dom.min.js"></script>
<script src="https://cdn.bootcss.com/babel-standalone/6.22.1/babel.min.js"></script>
</head>
<body>
<div id="text"></div>
<script type="text/babel">
var SayHello=React.createClass({
render:function(){
return <p>Hello {this.props.name}</p>;
}
});
ReactDOM.render(
<SayHello name="pangtong" />,
document.getElementById("text")
);
</script>
</body>
</html>
2, Set the default value for props through getDefaultProps() method
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>by props Set default</title>
<script src="https://cdn.bootcss.com/react/15.4.2/react.min.js"></script>
<script src="https://cdn.bootcss.com/react/15.4.2/react-dom.min.js"></script>
<script src="https://cdn.bootcss.com/babel-standalone/6.22.1/babel.min.js"></script>
</head>
<body>
<div id="text"></div>
<script type="text/babel">
var SayHello=React.createClass({
getDefaultProps:function(){
return {
name:'pangpang'
};
},
render:function(){
return <p>Hello {this.props.name}</p>;
}
});
ReactDOM.render(
<SayHello />,
document.getElementById("text")
);
</script>
</body>
</html>
3, Combining State and Props
Using state and props together in the application, you can set state in the parent component and pass it to the child component by using props on the child component.
Get the data passed by the parent component in the render function.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Combined use in application state and props</title>
<script src="https://cdn.bootcss.com/react/15.4.2/react.min.js"></script>
<script src="https://cdn.bootcss.com/react/15.4.2/react-dom.min.js"></script>
<script src="https://cdn.bootcss.com/babel-standalone/6.22.1/babel.min.js"></script>
</head>
<body>
<div id="text"></div>
<script type="text/babel">
var Name = React.createClass({
render:function(){
return (
<p>{this.props.name}</p>
);
}
});
var Link = React.createClass({
render:function(){
return (
<a href={this.props.site}>
{this.props.site}
</a>
);
}
});
var WebSite = React.createClass({
getInitialState:function(){
return {
name:'Baidu',
site:'https://www.baidu.com'
};
},
render:function(){
return (
<div>
<Name name={this.state.name} />
<Link site={this.state.site} />
</div>
);
}
});
ReactDOM.render(
<WebSite />,
document.getElementById("text")
);
</script>
</body>
</html>
Posted by The Eagle on Thu, 02 Apr 2020 22:10:33 -0700