绑定事件到状态
官方实现
安装
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>
)
}
}
其它实现
安装
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>
)
}
}
本文介绍了一种使用React进行状态管理的方法,通过`react-link-state`和`linkstate`库简化了组件状态与输入元素之间的绑定过程。展示了如何利用这些工具在React应用中实现简洁的状态同步。

492

被折叠的 条评论
为什么被折叠?



