我有两个组件,一个父(ManySpace
)和一个子(OtherComponent
)。 OtherComponent
渲染两个ManySpace
组件,并为manyspace
道具使用两个不同的数组。
MANYSPACE1和MANYSPACE2渲染是完美的,但是由于我如何解决此问题而使第一个ManySpace和第二个ManySpace组件数组内容感到困惑。
希望我能解释我的问题
import React, { Component } from 'react'; //and other imports
let MANYSPACE;
let icerik;
let firsttext;
let firstinput;
let answer1;
let answerlength1;
let secondtext;
let secondinput;
class ManySpace extends Component {
render() {
MANYSPACE = this.props.manyspace;
icerik = MANYSPACE[0].icerik;
firsttext = MANYSPACE[0].firsttext;
firstinput = MANYSPACE[0].firstinput;
if (firstinput) {
answer1 = MANYSPACE[0].firstinput.answer1;
answerlength1 = answer1.length;
}
secondtext = MANYSPACE[0].secondtext;
secondinput = MANYSPACE[0].secondinput;
if (secondinput) {
answer2 = MANYSPACE[0].secondinput.answer2;
answerlength2 = answer2.length;
}
return (
)
}
-我的其他组件
import React, { Component } from 'react'; //and other imports
const MANYSPACE1 = [
{
icerik: 'lorem ipsum',
firsttext: 'lorem ipsum',
firstinput: {
answer1: 'lorem ipsum'
},
secondtext: 'lorem ipsum'
}
];
const MANYSPACE2 = [
{
icerik:'lorem ipsum',
firsttext: 'lorem ipsum',
firstinput: {
answer1: 'lorem ipsum'
},
secondtext: 'lorem ipsum',
secondinput: {
answer2: 'lorem ipsum'
},
thirdinput: {
answer3: 'lorem ipsum'
}
}
];
class OtherComponent extends Component {
<ManySpace
manyspace={MANYSPACE1}
/>
<ManySpace
manyspace={MANYSPACE2}
/>
}
最佳答案
在render
方法内部创建变量,而不是为所有ManySpace
实例共享一个变量。
例
import React, { Component } from "react"; //and other imports
class ManySpace extends Component {
render() {
const MANYSPACE = this.props.manyspace;
const { icerik, firsttext, firstinput } = MANYSPACE[0];
let answer1, answerlength1;
if (firstinput) {
answer1 = MANYSPACE[0].firstinput.answer1;
answerlength1 = answer1.length;
}
const { secondtext, secondinput } = MANYSPACE[0];
let answer2, answerlength2;
if (secondinput) {
answer2 = MANYSPACE[0].secondinput.answer2;
answerlength2 = answer2.length;
}
return (
{/* ... */}
);
}
}