[PReact] Use Link State to Automatically Handle State Changes
Posted Answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[PReact] Use Link State to Automatically Handle State Changes相关的知识,希望对你有一定的参考价值。
Storing and updating values inside a component’s local state (known as controlled components) is such a common pattern that Preact offers a really handy feature called ‘link state’ that not only removes the need to bind class methods, but also handles the setting of new values. This can remove the need for ‘setter’ style methods on classes and in this lesson we’ll look at an example of tracking the value of a ‘text input’.
Install:
yarn add linkstate
import {h, Component} from ‘preact‘; import linkState from ‘linkstate‘; export default class TextInput extends Component { render(props, {text = ‘‘}) { return ( <div> <input type="text" value={text} onInput={linkState(this, ‘text‘)}/> <pre><code>{JSON.stringify(this.state, null, 2)}</code></pre> </div> ) } }
linkState will help to call ‘this.state.setState‘, (this, ‘text‘), first ‘this‘ is the context, in which context, you want to call setState, second ‘text‘ is the prop name of the state.
以上是关于[PReact] Use Link State to Automatically Handle State Changes的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 Preact 和 TypeScript 对子组件进行类型检查?
一份来自Treebo 的 React 与 Preact PWA 性能分析报告