zl程序教程

您现在的位置是:首页 >  其它

当前栏目

[PReact] Use Link State to Automatically Handle State Changes

to use State Link handle changes
2023-09-14 09:00:51 时间

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.