使用React js将父Div附加到另一个Div

时间:2019-10-02 13:53:35

标签: reactjs frontend appendchild

我想用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'));
}

2 个答案:

答案 0 :(得分:1)

考虑以下React代码段

它使用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>
  );
}

答案 1 :(得分:1)

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

具有背景颜色属性的一个组件Parent

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

一个具有Children属性的组件border

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

还有一个Component,根据布尔值Parent仅显示visible或两个组件:

<Parent>{visible ? <Child /> : null}</Parent>

完整部分:

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

相关问题