【问题标题】:Append a parent Div for another Div with React js [closed]使用 React js 为另一个 Div 附加父 Div [关闭]
【发布时间】:2019-10-02 13:53:35
【问题描述】:

我想用 react js 做这个http://jsfiddle.net/bosworth99/ejdRf/4/

<div id="wrapper">
  <div id="slides"></div>
</div>

function wrap() {
  var newDiv = document.createElement('div');
  newDiv.setAttribute("id", "slideInner");
  document.getElementById('wrapper').appendChild(newDiv);
  newDiv.appendChild(document.getElementById('slides'));
}

【问题讨论】:

  • 您应该提供您为解决问题所做的工作。

标签: reactjs frontend appendchild


【解决方案1】:

有多种方法可以做到这一点。一种方法可能如下:

一个带有 background-color 属性的组件Parent

function Parent({ children }) {
  return (
    <div style={{ height: "100px", width: "100px", backgroundColor: "red" }}>
      {children}
    </div>
  );
}

具有border 属性的一个组件Children

function Child() {
  return (
    <div
      style={{
        boxSizing: "border-box",
        height: "100px",
        width: "100px",
        border: "4px solid black"
      }}
    />
  );
}

还有一个 Component 仅显示 Parent 或两个组件,具体取决于布尔值 visible

&lt;Parent&gt;{visible ? &lt;Child /&gt; : null}&lt;/Parent&gt;

完整的组件:

function App() {
  const [visible, toggleVisible] = useState(false);
  return (
    <>
      <div className="App">
        <button onClick={() => toggleVisible(!visible)}>Show Parent</button>       
        <Parent>{visible ? <Child /> : null}</Parent>
      </div>
    </>
  );
}

工作示例:https://codesandbox.io/s/crazy-thunder-voy1r

【讨论】:

    【解决方案2】:

    考虑下面的 React sn-p

    它使用 react-hooks 知道一个状态值 inner 并根据它的值动态生成 dom 结构

    import React, {useState, useEffect} from 'react';
    
    const Slide = () => {
      const [inner,setInner] = useState(false); //using react hooks for cleaner code, you can use class based states also
      useEffect(() => {
        setTimeout(() => setInner(true),2500); //same as the logic in the fiddle shared
      },[]) // same as ComponentDidMount in class based component
    
      const getWrappedDOM = () => {
        if(inner) {
          return (<div id="slideInner"><div id="slides"></div></div>);
        } else {
          return (<div id="slides"></div>);
        }
      }
    
      return (
        <div id="wrapper">
          {getWrappedDOM(); // generates the required DOM structure}
        </div>
      );
    }
    

    【讨论】:

    • 我需要类似 newDiv.appendChild(document.getElementById('slides'));附加到现有元素,因为我在
      中有很多节点,所以我不能把你的条件放在上面
    猜你喜欢
    • 2018-11-30
    • 1970-01-01
    • 2015-10-03
    • 2013-05-27
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多