提问人:cj- 提问时间:3/3/2021 更新时间:3/3/2021 访问量:1140
在子元素之前或之后呈现
Render before or after child element
问:
如何在容器中的子元素之前或之后呈现?
我正在通过将 React 集成到我自己的网站中来学习它。我从这个开始:
function createErrorSection(name, title, description) {
const section = document.createElement('section');
const container = document.createElement('div');
const h2 = document.createElement('h2');
const p = document.createElement('p');
section.appendChild(container);
container.appendChild(h2);
container.appendChild(p);
section.id = name;
section.classList = 'section-error';
container.classList = 'section-error-container';
h2.textContent = title;
p.textContent = description;
return section;
}
我变成了这个:
function createErrorSection(name, title, description) {
return (
<section id={name} className='section-error'>
<div className='section-error-container'>
<h2>{title}</h2>
<p>{description}</p>
</div>
</section>
);
}
这最终会传播到 either 或 。node.before(section)
node.after(section)
我检查了 ReactDOM、ReactDOM/server 和 React,但没有运气。我看到我可以创建一个 HTML 字符串,但我需要一个 HTMLElement,如果可以避免的话,我宁愿不做自己的渲染(我想学习 React 方式,我已经知道原版方式了)。
我的最终目标是学习如何以及何时正确使用 React。我很想知道正确的方法,但也非常感谢洞察力、建议和解决方法!
答:
在 React 中,你更愿意创建一个带有单个参数的自定义组件,其中包含相应的属性:
// single argument contains all props
function ErrorSection({name, title, description}) {
return (
<section id={name} className='section-error'>
<div className='section-error-container'>
<h2>{title}</h2>
<p>{description}</p>
</div>
</section>
);
}
现在,您需要导入ReactDOM
并调用,以便在具有id 的HTML节点中显示具有某些特定属性值的组件。确保您的 HTML 文档包含这样的节点。render
ErrorSecion
#app
import ReactDOM from "react-dom";
ReactDOM.render(
<ErrorSection name="..." title="..." description="..." />,
document.querySelector("#app")
);
大多数 react 应用程序使用文档正文中的单个空 HTML 节点(例如 div#app 或 div#root)将一些动态生成的嵌套组件渲染到 DOM 中。因此,您很可能只需要在整个项目中进行一次调用。ReactDOM.render
评论
首先,组件的名称应该写在PascalCase中。
在 React 中,你应该重新思考渲染元素的方式。
对于不同的目的,有不同的方法:
- 将组件传递给道具
children
const Wrapper = ({ children }) => (
<div className="wrapper">
<h1>Wrapper heading</h1>
{children}
</div>
);
现在,您可以通过以下方式将子项传递给包装器:
const AnotherComponent = () => (
<Wrapper>
<div>Element that will be rendered where the children prop is placed</div>.
</Wrapper>
);
- 将组件传递给自定义道具:
如果需要在不同位置渲染多个组件,可以这样做:
const MultiSpotComponent = ({ HeaderComponent, FooterComponent }) => (
<div>
{HeaderComponent}
<div>Some content</div>
{FooterComponent}
</div>
);
然后将组件传递给 props,就像在 HTML 中处理属性一样:
<MultiSpotComponent HeaderComponent={CustomHeader} FooterComponent={CustomFooter} />
请注意,我为组件使用了自闭合标记,因为我没有在其中渲染子项。
- 渲染列表
const AnotherComponent = () => {
const dynamicArray = ['some', 'dynamic', 'values'];
return (
<div>
{dynamicArray.map(value => <div key={value}>{value}</div>)}
</div>
);
};
我只描述了 3 种最常用的方法,但还有更多渲染元素的方法。你可以在官方 React 文档中了解更多信息
评论