如何将子元素传递给父元素,然后使用 React 渲染它?
我的代码示例:
let persons = [{name: 'Bill', age: '25'}, {name: 'John', age: '35'}]; // etc etc
function showPersons(data) {
data = persons;
let fatherDiv = <div></div>;
for (let i = 0; i < data.length; i++) {
let person = <span>Name: {data[i].name}, age: {data[i].age}</span>
fatherDiv.appendChild(person); //here's the error
}
ReactDOM.render(fatherDiv, document.getElementById('app'));
}
ReactDOM.render(
<button onClick={showPersons}>Show</button>,
document.getElementById('app')
);
<div id="app"></div>
PS 我是 React 的新手
答案 0 :(得分:0)
试试这个方法:
function showPersons() {
const result = persons.map((person, index) => (
<div key={index}>
<span>
Name: {person.name}, age: {person.age}
</span>
</div>
));
ReactDOM.render(result, document.getElementById("root"));
}
访问查看完整代码Working solution live demo
答案 1 :(得分:0)
您应该首先了解 React 库的基本概念以及如何使用它来操作 DOM 元素。
一个好的起动。将the official documentation其中通过在一个时间的不同概念一步进入步骤。
在 React 中,您不应该像使用 appendChild
那样操作 DOM 元素,相反,您应该创建新的或更新的 ReactElement
类型(可以通过 Javascript API 以编程方式或使用 JSX ~ 您可以在链接的文档中阅读更多内容)。
这里是如何实现相同的行为,即更新渲染的内容,尽管 React 方式:
import React from "react";
import ReactDOM from "react-dom";
export default function App() {
const persons = [{ name: "Bill", age: "25" }, { name: "John", age: "35" }];
const showPersons = () => {
const fatherDiv = persons.map(data => (
<span>
Name: {data.name}, age: {data.age}
<br />
</span>
));
ReactDOM.render(fatherDiv, document.getElementById("app"));
};
return (
<div>
<button onClick={showPersons}>Show</button>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
同时,这不应该是更新渲染内容的方式,通常您只需要在安装根组件时调用一次 ReactDOM#render
。可以使用 React 组件的状态来实现所需的行为:
import React, { useState } from "react";
import ReactDOM from "react-dom";
export default function App() {
// this is your data store (can also be any external data source
const persons = [{ name: "Bill", age: "25" }, { name: "John", age: "35" }];
// this is your component state, you can think of it as the live data within the component which may change along the lifecycle of the component
const [data, setData] = useState([]);
// this is the function that will be called to show persons by *just updating the state* and React will take care of re-rendering the component for us
const showPersons = () => {
setData(persons);
};
// this is the function that will be called to hide persons showed previously by *just updating the state as well* and React will take care once again of re-rendering the component for us
const hidePersons = () => {
setData([]);
};
return (
<div>
<button onClick={showPersons}>Show</button>
<button onClick={hidePersons}>Hide</button>
<div id="content">
{data.map(person => (
<span>
Name: {person.name}, age: {person.age}
<br />
</span>
))}
</div>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
在这里您可以检查状态操作的 a live demonstration。