react基础语法(五) state和props区别和使用
props的验证:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<!-- 生产环境中不建议使用 -->
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
<script src="https://cdn.bootcss.com/prop-types/15.6.1/prop-types.js"></script>
</head>
<body>
<div id="app">
</div>
<script type="text/babel">
//props验证借助第三方库 prop-types.js
var title = "验证传过来的数据类型是否正确?";
//var title = 666;
class Title extends React.Component {
render() {
return (
<h1>得到的props验证:{this.props.title}</h1>
);
}
}
Title.propTypes = {
title: PropTypes.string //属性 title 是必须的且是字符串,非字符串类型会自动转换为字符串并且控制台警告如title = 666;
};
ReactDOM.render(
<Title title={title} />,
document.getElementById('app')
);
</script>
</body>
</html>
state和props的互用:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<!-- 生产环境中不建议使用 -->
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>
<div id="app">
</div>
<!--Props验证-->
<!--React.PropTypes在 React v15.5 版本后已经移到了 prop-types 库。-->
<!--<script src="https://cdn.bootcss.com/prop-types/15.6.1/prop-types.js"></script>-->
<script type="text/babel">
//state和 props主要的区别在于 props是不可变的,而 state可以根据与用户交互来改变;
//子组件只能通过 props来传递数据;
//组合使用 state 和 props;
class WebSite extends React.Component {
constructor() {
super();
this.state = { //父组件中设置 state,并通过在子组件上使用 props将其传递到子组件上;
name: "react基础语法",
website: "https://www.baidu.com"
}
}
render() {
//设置 name和 website来获取父组件传递过来的数据
return (
<div>
<Name name={this.state.name} />
<Web website={this.state.website} />
</div>
);
}
}
class Name extends React.Component {
render() {
return (
<h1>{this.props.name}</h1>
);
}
}
class Web extends React.Component {
render() {
return (
<a href={this.props.website}>
{this.props.website}
</a>
);
}
}
ReactDOM.render(
<WebSite />,
document.getElementById('app')
);
</script>
</body>
</html>