是否可以在不使用ref的情况下调用dom元素方法(如focus())?(无状态组件功能)

Bal*_*nry 10 reactjs

我尝试尽可能少地使用refs,但似乎没有办法调用本机dom方法(focus(),reset(),blur()等)所以我没关系.除此之外,我想将新的无状态组件函数用于表单输入这样的基本事物,就目前而言,这些无状态组件不允许refs指向它们(它们将返回null).我知道我可以在无状态组件周围添加一个常规的React类组件包装器,以允许ReactDOM.findDOMNode(ref)正常工作,但如果始终必须包装无状态函数又有什么意义呢?我错过了什么吗?

Bal*_*nry 7

这是我提出的一个解决方案,它不需要在类中包装无状态组件.相反,它涉及父函数将函数作为prop传递给无状态组件,该函数用作DOM元素上的ref的回调函数.

首先在有状态父对象上设置一个方法,该方法将用作对ref的回调,另一种方法是对DOM元素进行操作(在这种情况下,在按下按键后进行聚焦).然后将该方法作为道具发送给无国籍儿童.

// note: Facebook now recommends using native js classes instead of React.createClass().
// note 2: You may need Babel to transpile some of ES6 syntax in use here.

const StatefulParent = React.createClass({
  getInitialState() {
    return {
      // doesn't matter for this example
    }
  },
  componentDidMount() {
    document.addEventListener('keyup', this.keyUp, false)
  },
  keyUp() {
    // calls the DOM focus method on the input when the 'tab' key is pressed
    if (e.keyCode === 9) this._input.focus()
  },
  inputSetter(ref) {
    this._input = ref
  },
  render() {
    <StatelessTextInput {...this.state} refCallback={this.inputSetter} />
  }
})
Run Code Online (Sandbox Code Playgroud)

无状态组件假定一个方法将从父级调用refCallback传递给它.该prop可以传递任意数量的组件生成以到达DOM元素.

const StatelessTextInput = ({refCallback, ...props}) => (
  <input {...props} ref={refCallback} />
)
Run Code Online (Sandbox Code Playgroud)