[React] Public Class Fields with React Components
React with Class Components public fields
2023-09-14 08:59:18 时间
Public Class Fields allow you to add instance properties to the class definition with the assignment operator (=
). In this lesson, we'll look at their use case for simplifying event callbacks and state initialization with a React component.
Handle function:
// Better handleClick = () => { ... } // Not good constructor() { super(); this.handleClick = this.handleClick.bind(this); } handleClick() { ... }
Handle State:
// Better state = {count: 0} // Not good constructor() { super(); this.state = {count: 0}; }
Using puiblic field, we can actually remove 'constructor' because it is no longer necessary.
class App extends React.Component { state = {clicks: 6} handleClick = () => { this.setState(prevState => { return {clicks: prevState.clicks + 1} }) } render() { return ( <div> <div> Click Count: {this.state.clicks} </div> <button onClick={this.handleClick} > Click Me! </button> </div> ) } } ReactDOM.render( <App />, document.getElementById('root') )
相关文章
- React Context源码是怎么实现的呢
- 小前端读源码 - React组件更新原理
- React v18.x 在 react-router v6 使用 lazy 动态加载组件实现
- 优雅地乱玩 Redux-2-Usage with React
- React中路由传参问题
- react的jsx和React.createElement是什么关系?面试常问
- 一天梳理React面试高频知识点
- react源码分析:深度理解React.Context_2023-02-28
- 从源码角度看React-Hydrate原理
- React源码之深度理解diff算法
- react源码之fiber架构
- 从react源码角度看React-Hydrate原理
- React源码学习入门(十二)DOM组件更新流程与Diff算法
- 配置无须导入react就可以使用jsx
- WordPress 官方宣布停用 React
- React 许可证虽严苛,但不必过度 react
- 探索React框架中MySQL数据库的应用(react mssql)