React 使用 linkState 組件 原

綁定事件到狀態

官方實現

npm

安裝

npm install react-link-state --save

使用示例

import React from 'react';
import linkState from 'react-link-state';
 
export default MyForm extends React.Component {
  constructor(props) {
    super(props);
 
    this.state = {
      username: '',
      password: '',
      toggle: false
    };
  }
 
  render() {
    console.log(this.state);
    
    return (
      <form>
        <input type="text" valueLink={linkState(this, 'username')} />
        <input type="password" valueLink={linkState(this, 'password')} />
        <input type="checkbox" checkedLink={linkState(this, 'toggle')}
      </form>
    );
  }
}

使用示例2

import linkState from 'react-link-state'

class Demo extends Component {
    constructor(props) {
        super(props)
        this.state = {
            text: ''
        }
    }

    render() {
        const {text} = this.state
        return (
            <div>
                <input valueLink={linkState(this, 'text')} type="text"/>
            </div>
        )
    }
}

 

其它實現

github

安裝

npm install --save linkstate

用法示例

import linkState from 'linkstate';

class Foo extends Component {
  state = {
    text: ''
  };
  render(props, state) {
    return (
      <input
        value={state.text}
        onInput={linkState(this, 'text')}
      />
    );
  }
}

用法示例2

import linkState from 'linkstate'

class Demo extends Component {
    constructor(props) {
        super(props)
        this.state = {
            text: ''
        }
    }

    render() {
        const {text} = this.state
        return (
            <div>
                <input value={text}  onInput={linkState(this, 'text')} type="text" />
            </div>
        )
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章