我正在使用<Tuner />
为this.state.notes
数组中的每个项目渲染一个this.state.notes.map()
组件。我想知道是否有一种方法可以分别对每个组件进行样式设置。我想将它们分别放置在页面上,但是它们都被一起渲染了,所以如果我没记错的话,内联样式或className都不起作用。该怎么办?
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]}
/>
));
答案 0 :(得分:0)
您可以使用预定义样式,并使用className
或内联样式but less recommended生成它们,如下所示:
import React from 'react';
import ReactDOM from 'react-dom';
import './noteStyles.css';
const notes = [{ note: 'A' }, { note: 'B' }];
const NOTE_STYLE = {
B: {
color: 'pink'
},
A: {
color: 'palegreen'
}
};
const App = () => {
return (
<>
{notes.map(({ note }) => (
<div className={`noteStyle${note}`} style={NOTE_STYLE[note]}>
{note}
</div>
))}
</>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
答案 1 :(得分:0)
这是一个非常广泛的问题,因为您尚未真正描述所需的样式,但我假设您想做一些简单的事情,例如更改音符的颜色。您可以采取几种方法:
this.state = {
notes: [{
note: "E",
tone: E,
color: "#ff0000",
}, {
note: "A",
tone: A,
color: "#ff00ff",
}, {
note: "D",
tone: D,
color: "#ff00aa",
}, {
note: "G",
tone: G,
color: "#112233",
}, {
note: "B",
tone: B,
color: "#ff0011",
}, {
note: "e",
tone: e,
color: "#ff1100",
}]
}
render() {
const notes = this.state.notes.map((note, index) => {
const colors = [
"#ff0000",
"#ff00ff",
"#ff00aa",
"#112233",
"#ff0011",
"#ff1100",
];
return (
<Tuner
key={note.note}
note={note.note}
color={colors[index]}
/>
);
});
.note:nth-child(1) { color: ... }