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