我正在使用 sub/pub 模式mufa在 React 组件之间而不是 props 之间进行通信。然后,我们将减轻父组件中的逻辑(正如您将在下面的代码片段中注意到的那样)。
const {on, fire} = mufa;
class Input extends React.Component {
onChange(event) {
fire('input_change', event.target.value);
}
render() {
return <input onChange={this.onChange.bind(this)} />
}
}
class Label extends React.Component {
state= {text: ""};
componentDidMount() {
on('input_change', this.onInputChange.bind(this));
}
onInputChange(inputValue) {
this.setState({text: inputValue});
// I need code to stop calling this method when inputValue reaches 10 characters.
}
render() {
return <label > {this.state.text} </label>
}
}
class App extends React.Component {
// No logic here thanks to the Sub/Pub pattern.
render() {
return (
<div>
<Label />
<Input/>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdn.rawgit.com/abdennour/mufa/ddf78fd9/cdn/mufa-latest.min.js"></script>
<div id="app" ></div>
我关心的是如何阻止这种沟通Label
and Input
当输入值达到 10 个字符时。
我试过这个:
onInputChange(inputValue) {
if (inputValue.length <= 10 ) // <-- I add this.
this.setState({text: inputValue});
}
然而,这种情况并不妨碍调用onInputChange
。我的目标是停止此订阅(以input_change
事件)当输入立即达到 10 个字符时。
看起来像mufa
有一种取消订阅的方法,如下所示:
const mufa = new Mufa();
const {on, fire, unsub} = mufa;
class Input extends React.Component {
onChange(event) {
fire('input_change', event.target.value);
}
render() {
return <input onChange={this.onChange.bind(this)} />
}
}
class Label extends React.Component {
state= {text: ""};
constructor(props) {
super(props);
this.sub = null;
}
componentDidMount() {
this.sub = on('input_change', this.onInputChange.bind(this));
}
onInputChange(inputValue) {
if(inputValue.length >= 10) {
unsub(this.sub);
return;
};
this.setState({text: inputValue});
// I need code to stop calling this method when inputValue reaches 10 characters.
}
render() {
return <label > {this.state.text} </label>
}
}
class App extends React.Component {
// No logic here thanks to the Sub/Pub pattern.
render() {
return (
<div>
<Label />
<Input/>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://abdennour.github.io/mufa/mufa-latest.min.js"></script>
<div id="app" ></div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)