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>
        )
    }
}

 

转载于:https://my.oschina.net/lemos/blog/1531052

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值