123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8" />
- <meta http-equiv="X-UA-Compatible" content="IE=edge" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>Document</title>
- <script src="../../babel.min.js"></script>
- <script src="../../react.development.js"></script>
- <script src="../../react-dom.development.js"></script>
- </head>
- <body>
- <div id="root"></div>
- <script type="text/babel">
- function App() {
- // 需要 我们自己创建一个对象(ref对象 ==> {current: 组件实例}) 和 要获取的组件 建立ref绑定关系
- const counterRef = React.createRef();
- const inputRef = React.createRef();
- return (
- <div className="app">
- <button
- onClick={() => {
- console.log(`output->counterRef`, counterRef);
- console.log(`output->inputRef`, inputRef);
- }}
- >
- 获取Counter组件实例
- </button>
- <input type="text" ref={inputRef} />
- {/*通过组件元素的ref属性 和 上面创建的ref对象 建立绑定关系*/}
- <Counter ref={counterRef} />
- </div>
- );
- }
- class Counter extends React.Component {
- constructor(props) {
- super(props);
- this.state = {
- c: 0,
- };
- this.handleAddOne = this.handleAddOne.bind(this);
- }
- handleAddOne() {
- // this
- // ? this.state.c 是上一次状态吗。不一定。因为 setState状态的更新 可能是异步的
- // 如果当前新状态 的值 需要依赖 上一次状态的值 运算才能计算出 这个时候 就不能像下面方式写
- // this.setState({ c: this.state.c + 1 });
- // 为了 准确获取上一次状态 可以给 setState方法 传入一个回调函数:该函数会接收两个参数:prevState、props。传入的回调函数 在返回一个新的状态对象即可
- this.setState((prevState) => {
- return { c: prevState.c + 1 };
- });
- }
- render() {
- let { c } = this.state;
- return (
- <div className="counter">
- <p>当前计数:{c}</p>
- <p>
- <button
- onClick={() => {
- // this
- this.setState(({ c }) => ({ c: c - 1 }));
- }}
- >
- -
- </button>
- <button onClick={this.handleAddOne}>+</button>
- </p>
- </div>
- );
- }
- }
- const root = ReactDOM.createRoot(document.querySelector('#root'));
- root.render(<App />);
- </script>
- </body>
- </html>
|