如何更新使用 ReactDOM.render() 渲染的 React 组件的 props

rex*_*rex 6 javascript reactjs react-dom angular

我正在尝试将 react 集成到我的 angularjs webapp 中。

在我的控制器中,我创建了一个组件,它最初具有空的数组道具。当应用程序完成初始化后,我想再次更新道具。我是通过ReactDOM.render()再次调用来做到这一点,还是可以保留对此实例的引用并执行类似的操作updateProps(newProps)

这是从我的控制器调用的:

ReactDOM.render(
    <NavBar
        currencyTabs = {[]}
    />, document.getElementById("navbar-root")
);
Run Code Online (Sandbox Code Playgroud)

然后当数据加载完成后,我需要currencyTabs用完整的数组更新......

我了解 react 组件 props 如何从父级更新到子级,但我不太明白如何从纯 JS 中做到这一点。

Ice*_*kle 6

这里没有魔法在起作用,你只需要重新渲染它。

只需将您的渲染包装到一个函数中,例如:

function renderReactNavbar( tabs = [] ) {
  ReactDOM.render(
    <NavBar
        currencyTabs = { tabs }
    />, document.getElementById("navbar-root")
  );

}
Run Code Online (Sandbox Code Playgroud)

并在加载/更新数据后调用它。

或者,您选择从 react 内部加载数据,从长远来看这可能是更好的选择。

如果您有内部状态,这可能有点难以处理。您可以考虑迁移到仅支持 props 的组件(但由于您不共享 react 组件的任何相关代码,因此很难说)

它看起来如何的一个小例子是

function renderReactNavbar( tabs = [] ) {
  ReactDOM.render(
    <NavBar
        currencyTabs = { tabs }
    />, document.getElementById("navbar-root")
  );

}
Run Code Online (Sandbox Code Playgroud)
// the render method, takes a component and props, and renders it to the page
function renderComponent( component, props ) {
  const target = document.querySelector('#container');
  ReactDOM.render( React.createElement( component, props ), target );
}

// gets the tabs from the input field, splits based on ,
function getTabsFromInput() {
  return document.querySelector('#tabs').value.split(',');
}

// small presentational component, shows the tabs and redirects selection changes through a callback
const Tabs = ({ tabs, selectedTab, onSelectionChanged }) => {
  return tabs && <div>{ tabs.map( (tab, key) => {
    return <h1 key={key} className={classNames( { 'active': key === selectedTab } ) } onClick={ () => onSelectionChanged( key ) }>{ tab }</h1>;
  } ) }</div>;
};

// some initiations
window.addEventListener('load', function() {
  // keep a local variable with the data
  let defaultProps = {
    onSelectionChanged: updateSelection,
    selectedTab: 0,
    tabs: getTabsFromInput()
  };

  // handles selection changes
  function updateSelection( newTab ) {
    defaultProps = {...defaultProps, selectedTab: newTab };
    renderComponent( Tabs, defaultProps );
  }

  // adds an event listener for click events to initiate tab changes
  document.querySelector('#updateTabs').addEventListener('click', function() {
    defaultProps = {...defaultProps, tabs: getTabsFromInput() };
    // render on update
    renderComponent( Tabs, defaultProps );
  });

  // initial render
  renderComponent( Tabs, defaultProps );
});
Run Code Online (Sandbox Code Playgroud)
.active {
  background-color: blue;
}
Run Code Online (Sandbox Code Playgroud)

  • 这个答案很好,但我误解了。因此,请注意,这可能对其他人有帮助:`ReactDom.render()` 不会给你一个干净的状态;它只是更新组件。所以如果你的 props 没有改变,它就不会重新渲染。如果您正在与一个不能完全正常运行的系统进行战斗,那么您必须首先执行“ReactDom.unmountComponetnAtNode()”(或者只是为了强制更新而引入一些其他道具)。有效果吗?好吧,现在寻找一些方法来删除该黑客:-) (5认同)