我正在寻找一种方法来替换旧系统中的阻塞prompt调用。它以阻止方式要求用户输入:
const name = prompt('name:', previousValue);
if (name) {...
我想用React组件替换它。我正在整个系统上为i18n使用redux和context,因此我试图找到一种优雅的方法来解决这个问题。我希望能够从应用程序中的每个方法调用它。
目前,我在根App组件中呈现了Prompt组件,并在传递回调的同时通过上下文将其公开:
class App extends Component {
getChildContext = () => {
return {
i18n: i18n,
prompt: this.prompt
}
};
state = {
showPrompt: null,
};
prompt = (title, value, callback) => {
this._prompt = {title, value, callback};
this.timeout = setTimeout(() => {
this.setState({showPrompt: true});
}, 100);
}
// ...class continues...
用法:
this.context.prompt('name', '', callback: (occurrences) => {
if (name) {
this.props.changeName(name);
}
}
});
但是肯定有人带来了更好的原因吗?