React.js 安装后实现 UI 效果

React.js implement UI effects after mounting

假设我有一个 React class,它有一个组件 - 带有 autosize.js and bootstrap form helpers phone 库的字段。有麻烦了。由于这几个(以及很多其他)库在 DOM 加载后呈现,我需要手动将这些库实现到组件 - 就像这样:

componentDidMount: ->
  phoneInput = $(React.findDOMNode(@refs.phone)) # found appropriate field
  phoneInput.bfhphone(phoneInput.data()) # approve bfh-phone for this field

如何让我的 React classes 在将它们安装到 DOM 之前已经使用这些 UI 库?

如@WiredPrairie 所说,要与非 React DOM 库集成,您需要使用 componentDidMount。但是,您可以将该逻辑封装在自定义组件中,这样您只需执行一次。例如,您使用了代码:

componentDidMount: ->
  phoneInput = $(React.findDOMNode(@refs.phone))
  phoneInput.bfhphone(phoneInput.data())

假设您有几个这样的字段。您可以创建一个名为 BFHPhoneInput 的特殊组件或自动为您完成的组件:

BFHPhoneInput = React.createClass
  componentDidMount: ->
    input = $(React.findDOMNode(@refs.input))
    input.bfhphone(input.data())

  render: ->
    props =
      ref: "input"
    # copy all this.props to props
    props[key] = val for own key, val of this.props
    React.DOM.input props

(我不熟悉 bfhphone 插件,因此您可能需要做更多的工作才能正确集成它。)

现在可以多次使用,不用担心插件问题了:

MyComponent = React.createClass
  render: ->
    React.DOM.div {},
      BFHPhoneInput {value: @state.phone1, onChange: @handlePhone1Change}
      BFHPhoneInput {value: @state.phone2, onChange: @handlePhone2Change}