如何将组件Country.js添加到组件Countries.js
我想在浏览器中显示:
姓名:法国
资本:巴黎姓名:俄罗斯
资本:莫斯科//第一个组件Country.js
import React, { Component } from 'react'
class Country extends Component {
render() {
const {data} = this.props;
return (
<div className = {'countryItem'}>
<p className = {'countryLabel'}>
Name: {{this.props.country.name}}
</p>
<p className= {'contactLabel'}>
Capital: {{this.props.country.capital}}
</p>
</div>
)
return (
<div>
{Country}
</div>
)
}
}
export default Country;
//第二个组件Countries.js
import React, { Component } from 'react'
import Country from './Country';
class Countries extends Component {
render() {
const {data} = this.props;
const Countries = data.map(country => {
return (
<li key = {country.id}>
<h2>{country.name}</h2>
<p>{country.capital}</p>
</li>
)
})
return (
<ul>
{Countries}
</ul>
)
}
}
export default Countries;
// Data.js
export default [
{
id: 1,
Name: 'France',
Capital: 'Paris
},
{
id: 2,
Name: 'Russia',
Capital: 'Moscow'
}]
// HTML
<body>
<div id="root"></div>
</body>
// App.js
import React, {Component} from 'react';
import CountryForm from './components/CountryForm';
import Countries from './components/Countries';
class App extends Component {
render() {
return (
<div>
<div><CountryForm /></div>
<div><Countries data={this.props.data}/></div>
</div>
)
}
}
export default App;
//的script.js
var app = React.createElement(App);
ReactDOM.render(app, document.getElementById('app'));
我想在浏览器中显示:
姓名:法国
资本:巴黎姓名:俄罗斯
资本:莫斯科感谢您的帮助
答案 0 :(得分:3)
您可以尝试以下操作。
var data = [
{
id: 1,
Name: 'France',
Capital: 'Paris'
},
{
id: 2,
Name: 'Russia',
Capital: 'Moscow'
}];
class Country extends React.Component {
render() {
return (
<div className = 'countryItem'>
<p className = 'countryLabel'>
Name: {this.props.name}
</p>
<p className= {'contactLabel'}>
Capital: {this.props.capital}
</p>
</div>
)
}
}
class Countries extends React.Component {
render() {
const style = {
listStyleType: 'none'
}
const {data} = this.props;
const countries = data.map(country => {
return (
<li key = {country.id}>
<Country name={country.Name} capital={country.Capital}
/>
</li>
)
})
return (
<ul style={style}>
{countries}
</ul>
)
}
}
class App extends React.Component {
render() {
return (
<div>
<div><Countries data={data}/></div>
</div>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
答案 1 :(得分:0)
这需要更多的代码重做,而不是我可以动态做的,但基本上你会想在Countries.js中做这样的事情:
rawCapture.truncate(0)
希望这能为您提供解决其余部分所需的信息。
答案 2 :(得分:0)
在Countries.js
的渲染功能中,您应该在返回结果时传播 countries数组,如下所示:
return (
<ul>
{ ...Countries } // you miss the spread operator
</ul>
)
此外,在您的示例代码中,您实际上并未重用Country
组件类。
你也应该像:
const countries = data.map(country => (
<li id={country.id}>
<Country name={country.name} capital={country.capital}>
</li>
))
并修改您的Country.js
。你的实际上太乱了。
有关如何撰写React的简洁说明,请参阅此处 组件:https://reactjs.org/docs/composition-vs-inheritance.html