<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="app"></div> </body> </html> <script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script> <script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script> <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script> <script src="https://cdn.bootcss.com/prop-types/15.6.1/prop-types.js"></script> <script type="text/babel"> // 使用jsx语法 class App extends React.Component { constructor (props) { super(props); this.state = { todoList: ['11', '22', '33'] }; this.addTodo = this.addTodo.bind(this) } addTodo (todo) { const {todoList} = this.state todoList.unshift(todo) this.setState({ todoList }) } render() { const { todoList } = this.state; return ( <div> Example <Add count={ todoList.length } addTodo={ this.addTodo }/> <List todoList={ todoList }/> </div> ) } } class Add extends React.Component { constructor(props) { super(props); this.add = this.add.bind(this) } add() { const todo = this.todoInput.value.trim(); if(!todo) return this.props.addTodo(todo) this.todoInput.value = '' } fnRef (input) { // 将 input元素 指定给todoInput return this.todoInput = input } render() { return ( <div> {/* ref写法一 */} {/* <input type="text" ref={input => this.todoInput = input} /> */} {/* ref写法二 */} <input type="text" ref={this.fnRef.bind(this)} /> <button onClick={ this.add }>add #{this.props.count + 1}</button> </div> ) } } Add.propTypes = { count: PropTypes.number.isRequired, addTodo:PropTypes.func.isRequired } class List extends React.Component { render() { const { todoList } = this.props return ( <ul> {todoList.map((todo, key) => (<li key={key}>{todo}</li>))} </ul> ) } } List.propTypes = { todoList: PropTypes.array.isRequired } ReactDOM.render(<App />, document.getElementById('app')); </script>
注意: react并不推荐过度使用ref,如果能通过state做到的事情,就不应该使用 refs 在你的 app 中“让事情发生”。
过度使用ref并不符合数据驱动的思想