是否可以在不呈现HTML的情况下使用React?

时间:2014-02-28 20:10:44

标签: javascript reactjs

我想知道是否可以使用React来执行逻辑并将数据发送回javascript函数,而不会渲染任何html。我想到的组件是你传递一些数据的东西,它会将数据发送回反应之外的javascript函数。我知道可以做到,我自己就完成了这个部分,但是我不确定如果不按需要渲染html你会怎么做。这甚至是反应的实际用例吗?

4 个答案:

答案 0 :(得分:61)

从React> = 16.2开始,可以使用以下任何版本:

render() { 
   return false; 
}

render() { 
   return null; 
}

render() { 
   return []; 
}

render() { 
   return <React.Fragment></React.Fragment>; 
}

render() { 
   return <></>; 
}

返回undefined不起作用。


  

我想到的组件是你传递一些数据的东西,   并且它会将数据发送回反应之外的javascript函数。

为什么要为此创建组件?大多数情况下,现有组件中的常规js函数就足够了。

例如,一个用例用于在安装组件时设置副作用,并在卸下组件时将其拆除。例如,如果你有一个纵向的ReactNative移动应用程序,你可以想象一个<Landscape/>组件,当安装时,它将允许暂时以横向显示应用程序,并且在卸载时,方向将重置为app默认。您可以在现有组件上管理此方向更改,但创建专用组件可能更方便且可重复使用。

请注意,React也可以在服务器端运行,所以我猜它可以以不涉及任何DOM修改的方式使用它(但可能只是虚拟DOM计算)。

答案 1 :(得分:22)

只是为了澄清本诺的评论。 ReactComponent.render method doc州:

  

您还可以返回nullfalse表示您不想要呈现任何内容。在幕后,React呈现<noscript>标签以使用我们当前的差异算法。返回nullfalse时,this.getDOMNode()将返回null

答案 2 :(得分:12)

有可能。 react-router是组件未呈现HTML的库的示例。见https://github.com/rackt/react-router

这是react-fouter的Route组件,render方法返回false:


const Route = React.createClass({

  statics: {
    createRouteFromReactElement
  },

  propTypes: {
    path: string,
    component,
    components,
    getComponent: func,
    getComponents: func
  },

  /* istanbul ignore next: sanity check */
  render() {
    invariant(
      false,
      '<Route> elements are for router configuration only and should not be rendered'
    )
  }

})

答案 3 :(得分:5)

是的,在延迟加载组件的情况下非常有用且非常有用。

请考虑使用react-router。

import React from 'react'
import { Route, Link } from 'react-router-dom'

function asyncComponent(getComponent) {
  return class AsyncComponent extends React.Component {
    static Component = null;
    state = { Component: AsyncComponent.Component };

    componentWillMount() {
      if (!this.state.Component) {
        getComponent().then(Component => {
          AsyncComponent.Component = Component
          this.setState({ Component })
        })
      }
    }
    render() {
      const { Component } = this.state
      if (Component) {
        return <Component {...this.props} />
      }
      return null
    }
  }
}

const Page1 = asyncComponent(() =>
  System.import('./Page1.js').then(module => module.default)
)
const Page2 = asyncComponent(() =>
  System.import('./Page2.js').then(module => module.default)
)
const Page3 = asyncComponent(() =>
  System.import('./Page3.js').then(module => module.default)
)

const ParentComponent = () => (
  <div>
    <ul>
      <li>
      <Link to="/page1">Page1</Link>
      </li>
      <li>
      <Link to="/page2">Page2</Link>
      </li>
      <li>
      <Link to="/page3">Page3</Link>
      </li>
    </ul>
    <div>
      <Route path="/page1" component={Page1}/>
      <Route path="/page2" component={Page2}/>
      <Route path="/page3" component={Page3}/>
    </div>
  </div>
)
相关问题