<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="build/react.js"></script>
<script src="build/react-dom.js"></script>
<script src="build/browser.min.js"></script>
</head>
<body>
<div id="container">
</div>
</body>
<script type="text/babel">
ReactDOM.render(
<h1>Hello,world</h1>
,
document.getElementById('container')
);
/*props 、state
props是组件自身的属性,一般用于嵌套的内外层组件中
负责传递信息(通常由父层组件向子层组件传递)
注意:props 对象中的属性与组件的属性一样对应,不要直接去修改props中属性的
...this.props
props 提供的语法糖 可以将付父件的全部属性都复制给子组件
需求:定义一个组件Link link组件只包含一个<a>,不给<a>设置任何属性,
所有属性由父组件获得
*/
/*let link = React.createClass({
render:function () {
return <a{ ...this.props }>{ this.props .name}</a>
}
});
ReactDOM.render(
<link href="https://www.baidu.com" name="baidu"/>,
document.getElementById("container")
);
/*
this.props.children
children是一个例外,不是跟组件的属性对应
表示组件的所有子节点
h5中有一种标签为列表:<ul> <ol> <li>
定义一个列表组件,列表项中显示的内容,
以及列表项的数量都由外部决定
*/
let ListComponent = React.createClass({
render:function () {
return(
<ul>
{
/*
// 列表项的数量、内容不确定,在创建模板是才能确定
// 利用this.props.children 从父组件获取需要展示的内容
// 获取到列表项内容后,需要遍历children,逐个进行设置
// 使用React.Children.map方法
// 返回值:数组对象 这个数组中的元素是<li>
// */
React.children.map(this.props.children,function (child) {
return<li>{child}</li>
})
}
</ul>
);
}
});
ReactDOM.render(
<ListComponent>
<h1>Hello World</h1>
<a href="https://www.baidu.com">https://www.baidu.com</a>
</ListComponent>,
document.getElementById("container")
);
/*
属性验证 propTypes
用于验证组件实例的属性是否复合要求
*/
let ShowTitle = React .createClass({
propTypes:{
title:React.PropTypes.string .isRequired
},
render:function () {
return<h1>{this.props.title}</h1>
}
});
ReactDOM.render(
<ShowTitle title="Hello World"/>,
<ShowTitle title="123" />,
document.getElementById("container")
);
/*
设置组件属性的默认值
通过实现组价的getDefaultProps方法 对属性设置默认值
*/
let MyTitle = React.createClass({
getDefaultProps:function () {
return{
title:"HelloWorld"
};
},
render:function () {
return<h1>{this.props.title}</h1>
}
});
ReactDOM.render(
<MyTitle/>,
document.getElementById("container")
)
</script>
</html>