gpt4 book ai didi

javascript - 在 React 中使用不同的 props 多次渲染组件

转载 作者:行者123 更新时间:2023-12-03 02:38:00 25 4
gpt4 key购买 nike

我有一个组件正在尝试渲染四次,每次都使用不同的 Prop 。为了让我的代码更加简洁,而不是每次都实际写出组件及其 props 的 JSX,我尝试使用 map 创建组件的不同实例。现在,看起来是这样的:

import React, { Component } from 'react';
import Panel from './components/Panel';
import Results from './components/Results';
import Intro from './components/Intro';

const questionsMap = [0, 1, 2, 3];

class React extends Component {
constructor (props) {
super (props);
this.state = {
questions: ['question1', 'question2', 'question3', 'question4'],
answers: ['answers1', 'answers2', 'answers3', 'answers4']
}
this.onSelect = this.onSelect.bind(this);
}

onSelect(value) {
/* Some code for when buttons are clicked */
}

render () {
return (
<Intro />
{questionsMap.map(i => {
return <Panel question={this.state.questions.i} answers={this.state.answers.i} onSelect={this.onSelect} />
})}
<Results />
);
}
}

export default App;

现在我收到一个 Unexpected token 错误,该错误指向我的渲染下以 {questionsMap.map()} 开头的行,也就是我所在的部分我正在尝试实际进行我提到的映射。我假设我使用了错误的语法来完成我想要的事情?

最佳答案

以下是正确的语法:

import React, { Component } from 'react';
import Panel from './components/Panel';
import Results from './components/Results';
import Intro from './components/Intro';

const questionsMap = [0, 1, 2, 3];

class React extends Component {
constructor (props) {
super (props);
this.state = {
questions: ['question1', 'question2', 'question3', 'question4'],
answers: ['answers1', 'answers2', 'answers3', 'answers4']
}
this.onSelect = this.onSelect.bind(this);
}

onSelect(value) {
/* Some code for when buttons are clicked */
}

render () {
return (
<div>
<Intro />
{questionsMap.map(i => {
return <Panel question={this.state.questions[i]} answers={this.state.answers[i]} onSelect={this.onSelect} />
})}
<Results />
</div>
);
}
}

export default App;

但是有一些事情并不完全是一个好的做法,我认为这是某种测试,所以我不希望您将其中一个组件命名为 React

最重要的是,您可以简单地映射状态,我会像这样更改代码:

import React, { Component } from 'react'; import Panel from './components/Panel'; import Results from './components/Results'; import Intro from './components/Intro';


class React extends Component {
constructor (props) {
super (props);
this.state = {
questions: ['question1', 'question2', 'question3', 'question4'],
answers: ['answers1', 'answers2', 'answers3', 'answers4']
}
this.onSelect = this.onSelect.bind(this);
}

onSelect(value) {
/* Some code for when buttons are clicked */
}

render () {
return (
<div>
<Intro />
{this.state.questions.map((question, questionIndex) => {
return (<Panel
question={question}
answers={this.state.answers[questionIndex]}
onSelect={this.onSelect} />
)
})}
<Results />
</div>
);
} }

export default App;

或者,您可以拥有一个对象数组,其中包含一个名为“问题”的字段和另一个名为“答案”的字段,只是为了给您提供另一个想法。

关于javascript - 在 React 中使用不同的 props 多次渲染组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48466844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com