阮一峰react-demo
1)
<script src="../build/react.development.js"></script>
<script src="../build/react-dom.development.js"></script>
<script src="../build/babel.min.js"></script>
ReactDOM.render( <h1>Hello, world!</h1>, document.getElementById('example') );2)
<script src="../build/react.development.js"></script>
<script src="../build/react-dom.development.js"></script>
<script src="../build/babel.min.js"></script>
let names = ['Alice', 'Emily', 'Kate']; ReactDOM.render( <div> { names.map((name, index)=> {
return <div key={index}>Hello, {name}!</div>
}) } </div>, document.getElementById('example') );
3)
<script src="../build/react.development.js"></script>
<script src="../build/react-dom.development.js"></script>
<script src="../build/babel.min.js"></script>
let arr = [ <h1 key="1">Hello world!</h1>, <h2 key="2">React is awesome</h2>, ]; ReactDOM.render( <div>{arr}</div>, document.getElementById('example') );
4)
<script src="../build/react.development.js"></script>
<script src="../build/react-dom.development.js"></script>
<script src="../build/babel.min.js"></script>
class HelloMessage extends React.Component { render() { return <h1>Hello {this.props.name}</h1>; } } ReactDOM.render( <HelloMessage name="John" />, document.getElementById('example') );
注:React.Children
是頂層API之一,為處理this.props.children
這個封閉的資料結構提供了有用的工具。
this.props
物件的屬性與元件的屬性一一對應,但是有一個例外,就是this.props.children
屬性。它表示元件的所有子節點。
參考:https://blog.csdn.net/uuihoo/article/details/79710318
5)
<script src="../build/react.development.js"></script>
<script src="../build/react-dom.development.js"></script>
<script src="../build/babel.min.js"></script>
class NotesList extends React.Component { render() { return ( <ol> { React.Children.map(this.props.children, function (child) { return <li>{child}</li>; }) } </ol> ); } } ReactDOM.render( <NotesList> <span>hello</span> <span>world</span> </NotesList>, document.getElementById('example') );
6)// 使用PropTypes進行型別檢查,宣告props的型別
參考:https://www.jianshu.com/p/2896acb5746b
<script src="../build/react.development.js"></script> <script src="../build/react-dom.development.js"></script> <script src="../build/babel.min.js"></script> <script src="../build/prop-types.js"></script>
var data = 123; class MyTitle extends React.Component { static propTypes = { title: PropTypes.string.isRequired, } render() { return <h1> {this.props.title} </h1>; } } ReactDOM.render( <MyTitle title={data} />, document.getElementById('example') );