【发布时间】:2019-11-17 17:26:28
【问题描述】:
我正在使用this.state.notes.map() 为我的this.state.notes 数组中的每个项目呈现一个<Tuner /> 组件。我想知道是否有办法单独设置这些组件的样式。我想将它们单独放置在页面上,但它们都被一起呈现,所以如果我没记错的话,内联样式或类名都不起作用。如何做到这一点?
this.state = {
notes: [
{ note: "E", tone: E },
{ note: "A", tone: A },
{ note: "D", tone: D },
{ note: "G", tone: G },
{ note: "B", tone: B },
{ note: "e", tone: e }
]}
render() {
const notes = this.state.notes.map(note => (
<Tuner
key={note.note}
note={note.note}
/>
));
return (
<div className="App">
<h1>Online Guitar Tuner</h1>
{notes}
</div>
);
}
编辑:我尝试了一些建议的解决方案,但似乎都没有奏效。
对于这个解决方案,样式显示在 React 控制台的渲染组件中,但没有应用实际样式。我想也许我只是在这里遗漏了一些小东西,因为样式存在于组件上但没有被应用。
constructor(props){
this.noteStyles = {
E: {
backgroundColor: "#4caf50",
border: "none",
color: "white",
padding: "15px 32px",
textAlign: "center",
textDecoration: "none",
fontSize: "16px"
}
};
this.state = {
notes: [
{ note: "E", tone: E },
{ note: "A", tone: A },
{ note: "D", tone: D },
{ note: "G", tone: G },
{ note: "B", tone: B },
{ note: "e", tone: e }
]}
}
const notes = this.state.notes.map(note => (
<Tuner
key={note.note}
playSound={e => this.playSound(e)}
note={note.note}
styles={this.noteStyles[note.note]}
/>
));
【问题讨论】:
标签: javascript css reactjs