码迷,mamicode.com
首页 > 其他好文 > 详细

[PReact] Use Link State to Automatically Handle State Changes

时间:2017-06-17 23:25:16      阅读:365      评论:0      收藏:0      [点我收藏+]

标签:lin   str   this   classes   log   tin   removes   sid   setting   

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

标签:lin   str   this   classes   log   tin   removes   sid   setting   

原文地址:http://www.cnblogs.com/Answer1215/p/7041559.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!