Javascript 如何“重置”一个 ReactJS 元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26358144/
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-08-22 22:47:40  来源:igfitidea点击:

How to 'reset' a ReactJS element?

javascriptreactjs

提问by fadedbee

I'm trying to 'reset' a ReactJS element.

我正在尝试“重置”一个 ReactJS 元素。

In this case, the element is 90%+ of the contents of the page.

在这种情况下,该元素占页面内容的 90% 以上。

I'm using replaceStateto replace the state of the element with with its initial state.

replaceState用它的初始状态替换元素的状态。

Unfortunately, sub-elements which have their own 'state' do not reset. In particular, form fields keep their contents.

不幸的是,具有自己“状态”的子元素不会重置。特别是,表单字段会保留其内容。

Is there a way of forcing a re-render of an element, which will also cause sub-elements to re-render, as if the page had just loaded?

有没有办法强制重新渲染一个元素,这也会导致子元素重新渲染,就好像页面刚刚加载一样?

回答by fadedbee

Adding a keyto the element forces the element (and all its children) to be re-rendered when that key changes.

key元素添加 a会强制该元素(及其所有子元素)在该键更改时重新呈现。

(I set the value of 'key' to simply the timestamp of when the initial data was sent.)

(我将 'key' 的值设置为发送初始数据时的时间戳。)

render: function() {
  return (
    <div key={this.state.timestamp} className="Commissioning">
      ...

回答by Chris Dolphin

The this.replaceState(this.getInitialState())method doesn't actually reset children that are inputs, if that's what you're looking for. For anyone looking to just reset their form fields, there is a standard DOM reset()function that will clear all the inputs in a given element.

this.replaceState(this.getInitialState())如果这就是您要查找的内容,该方法实际上不会重置作为输入的子项。对于任何只想重置表单字段的人来说,有一个标准的 DOMreset()函数可以清除给定元素中的所有输入。

So with React, it'd be something like this:

所以使用 React,它会是这样的:

this.refs.someForm.getDOMNode().reset();

Doumentation:

解释:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset

https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset

回答by nonkertompf

If it is a form you want to reset, you simply can use this

如果它是您要重置的表格,您只需使用它

// assuming you've given {ref: 'form'} to your form element
React.findDOMNode(this.refs.form).reset();

回答by Michelle Tilley

While I don't personally think you should store local, interim component state (like in-progress input boxes) in a centralized location (like a flux store) in most cases, here it may make sense, depending on how many you have, especially since it sounds like the inputs already have some server interaction/validation around them. Pushing that state up the component hierarchy or into some other central location may help a lot in this case.

虽然我个人认为你不应该在大多数情况下将本地的、临时的组件状态(如正在进行的输入框)存储在一个集中的位置(如通量存储),但在这里它可能是有意义的,这取决于你有多少,特别是因为听起来输入已经在它们周围进行了一些服务器交互/验证。在这种情况下,将该状态向上推送到组件层次结构或其他一些中心位置可能会有很大帮助。

One alternative idea off the top of my head is to use a mixin in components that might need to reset local state, and do some kind of event triggering, etc. to make it happen. For example, you could use Node's EventEmitteror a library like EventEmitter3with a mixin like this (warning: not tested, maybe best this as pseudocode :)

我脑子里的另一个想法是在可能需要重置本地状态的组件中使用 mixin,并执行某种事件触发等以使其发生。例如,您可以使用 NodeEventEmitterEventEmitter3之类的库和这样的 mixin(警告:未测试,最好将其作为伪代码:)

var myEmitter = new EventEmitter(); // or whatever

var ResetStateMixin = {
  componentWillMount: function() {
    myEmitter.on("reset", this._resetState);
  },

  componentWillUnmount: function() {
    myEmitter.off("reset", this._resetState);
  },

  _resetState: function() {
    this.replaceState(this.getInitialState());
  },

  triggerReset: function() {
    myEmitter.emit("reset");
  }
};

Then you could use it in components like so:

然后你可以在像这样的组件中使用它:

React.createClass({
  mixins: [ResetStateMixin],

  getInitialState: function() {
    return { ... };
  },

  onResetEverything: function() {
    // Call this to reset every "resettable" component
    this.triggerReset();
  }
});

This is very basic and pretty heavy handed (you can only reset all components, every component calls replaceState(this.getInitialState()), etc.) but those problems could be solved by extending the mixin a bit (e.g. having multiple event emitters, allowing component-specific resetStateimplementations, and so forth).

这是非常基本且非常繁重的(您只能重置所有组件,每个组件调用replaceState(this.getInitialState())等)但是可以通过稍微扩展 mixin 来解决这些问题(例如,具有多个事件发射器,允许特定于组件的resetState实现等)向前)。

It's worth noting that you dohave to use controlled inputs for this to work; while you won't need to push your state all the way up the component hierarchy, you'll still want all your inputs to have valueand onChange(etc.) handlers.

值得一提的是,你必须使用受控的投入这个工作; 虽然您不需要将状态一直向上推送到组件层次结构,但您仍然希望所有输入都具有valueonChange(等)处理程序。

回答by Vatsal Chauhan

You could also use

你也可以使用

document.forms[0].reset()