在输入onChange卡住期间反应改变父状态

时间:2016-09-25 15:45:44

标签: javascript reactjs

我正在构建一个由至少50个输入组成的巨大形式。 我在表单组件中编写了一个函数,它将输入值保存为表单状态:

家长功能

<FieldInput
  label="Name (as shown) *"
  part="information"
  element="displayName"
  saveToState={this.saveToState}
/>

通过儿童组件(输入)

import React, { Component } from 'react';
export default class FieldInput extends Component {
  render() {
    const { label, part, element, saveToState } = this.props;
    return (
      <div className="field">
        <label>{label}</label>
        <div className="ui input">
          <input
            type="text"
            name={`${part}[${element}]`}
            onChange={(e) => saveToState({
              part,
              element,
              value: e.target.value
            })}
          />
        </div>
      </div>
    );
  }
}

这是输入组件:

saveToState

结果每当我在输入中输入内容时它会以200-300ms的速度真实地显示我在输入中写的内容,状态会立即获得更新但是每当我输入一个字符时我都会设置父表单的新状态更新它更新整个组件。我发现它的唯一方法是在父组件中使用private void buildFitnessClient() { if (mClient == null && checkPermissions()) { mClient = new GoogleApiClient.Builder(this) .addApi(Fitness.SENSORS_API) .addScope(new Scope(Scopes.FITNESS_LOCATION_READ)) .addConnectionCallbacks( new GoogleApiClient.ConnectionCallbacks() { @Override public void onConnected(Bundle bundle) { Log.i(TAG, "Connected!!!"); // Now you can make calls to the Fitness APIs. findFitnessDataSources(); } @Override public void onConnectionSuspended(int i) { // If your connection to the sensor gets lost at some point, // you'll be able to determine the reason and react to it here. if (i == ConnectionCallbacks.CAUSE_NETWORK_LOST) { Log.i(TAG, "Connection lost. Cause: Network Lost."); } else if (i == ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) { Log.i(TAG, "Connection lost. Reason: Service Disconnected"); } } } ) .enableAutoManage(this, 0, new GoogleApiClient.OnConnectionFailedListener() { @Override public void onConnectionFailed(ConnectionResult result) { Log.i(TAG, "Google Play services connection failed. Cause: " + result.toString()); Snackbar.make( MainActivity.this.findViewById(R.id.main_activity_view), "Exception while connecting to Google Play services: " + result.getErrorMessage(), Snackbar.LENGTH_INDEFINITE).show(); } }) .build(); } } 而不传递它。但这需要1000行代码,有什么方法吗?谢谢!

1 个答案:

答案 0 :(得分:0)

有很多方法可以解决这个问题。最简单的一个是最快的一个是使用onBlur代替onChange setState,当您按下输入但输入失去焦点时,import React, { Component } from 'react'; export default class FieldInput extends Component { render() { const { label, part, element, saveToState } = this.props; return ( <div className="field"> <label>{label}</label> <div className="ui input"> <input type="text" name={`${part}[${element}]`} onBlur={(e) => saveToState({ part, element, value: e.target.value })} /> </div> </div> ); } } 将不会发生。{/ p>

// Gets rid of decimal places
mySimpleXYPlot.setDomainValueFormat(new DecimalFormat("0"));