寻找有关我可以做些什么来实现这一目标的一些提示。基本上,我有一个带有按钮的输入,可以快速进入。单击按钮时,需要模拟将值粘贴到用户光标所在的文本字段中。此外,如果有突出显示的内容,则应将其替换为输入的文本。
我正在使用redux-form的更改操作来立即更新值,这可以添加到最后 - 但不会产生我想要的效果。
答案 0 :(得分:2)
您在此处尝试实现的目标与默认情况下浏览器的行为方式不符。单击按钮将导致输入与光标位置一起失去其聚焦状态。当然,您可以通过重载组件状态来解决这个问题,但是当您添加更多输入和逻辑时,管理它可能会变得太多。
为了争论,我在这里发布了一个可能的解决方案,除非有充分的理由,否则我不会将其投放到生产中。
您需要将输入值存储在状态中,这是redux-form所做的,我在我的示例中使用了普通组件状态。每当您的焦点从输入移动到按钮(模糊事件)时,您将获得输入selectionStart
和selectionEnd
,并进行状态更新,用您的自定义替换原始输入值中它们之间的内容值。
就像我说的那样,在混合中添加多个输入会使问题复杂化,因为您需要将每个输入引用与状态键绑定。
class MyForm extends React.Component {
constructor() {
super();
this.state = {
inputValue: ''
}
}
render() {
return <form>
<input
value={this.state.inputValue}
ref={e => this.input = e}
onBlur={this.onBlurInput}
onChange={this.onInputChange}
/>
<br />
<button
ref={e => this.button = e}
type="button"
onClick={this.onAppend}
>
Append to cursor
</button>
</form>;
}
onBlurInput = (e) => {
// `e.target` is the input being blurred here
const stringToInsert = 'Hello World';
const {inputValue} = this.state;
const {selectionStart, selectionEnd} = e.target;
// We've clicked the button and the input has become blurred
if (e.relatedTarget === this.button) {
const newInputValue = inputValue.substring(0, selectionStart) +
stringToInsert +
inputValue.substring(selectionEnd);
this.setState({
inputValue: newInputValue
})
}
}
onAppend = (e) => {
// Re-focus the input
this.input.focus();
}
onInputChange = (e) => {
this.setState({
inputValue: e.target.value
});
}
}
ReactDOM.render(<MyForm />, document.getElementById('root'));
&#13;
<link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.2/normalize.min.css" rel="stylesheet" type="text/css" />
<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>
<div id="root"></div>
&#13;