javascript 我可以在 React 中将输入字段设置为只读,同时保留我的 onChange 函数吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31998198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:43:01  来源:igfitidea点击:

Can I set an input field to readonly in React while keeping my onChange function?

javascripthtmlreactjs

提问by jrader

I have the following React render function:

我有以下 React 渲染函数:

render: function() {
  return <input type="text" name="my-input-field" value={this.state.myObject} onChange={myFunction} />;
}

I would like to have this input field be readonly upon some condition that I have checked for. My understanding is that this input field would default to readonly if I didn't have the onChange function. Simply adding the readOnly tag hasn't worked for me.

我想让这个输入字段在我检查过的某些条件下是只读的。我的理解是,如果我没有 onChange 函数,则此输入字段将默认为只读。简单地添加 readOnly 标签对我不起作用。

How can i rewrite this so that I can later change the readonly status?

我如何重写它以便我以后可以更改只读状态?

回答by gusgol

You can use spread attributes to do that:

您可以使用传播属性来做到这一点:

render: function() {
  var opts = {};
  if( /* here your condition */ ) {
      opts['readOnly'] = 'readOnly';
  }

  return (
    <input 
      type="text" 
      name="my-input-field" 
      value={this.state.myObject} 
      onChange={myFunction} 
      {...opts} 
    />
  );
}