我通过mufa使用 sub/pub 模式在 React 组件而不是 props 之间进行通信。然后,我们将减轻 Parent 组件中的逻辑(您将在以下代码段中注意到这一点)。
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和Input当输入值达到10个字符。
我试过这个:
onInputChange(inputValue) {
if (inputValue.length <= 10 ) // <-- I add this.
this.setState({text: inputValue});
}
但是,此条件并不能阻止调用onInputChange. 我的目标是input_change在输入立即达到 10 个字符时停止此订阅(事件)。