[英]Having problem in putting headings in react
I am trying to put h1 heading, but if I put the only heading and comment out buttons then heading doesn't print.我正在尝试放置 h1 标题,但如果我放置唯一的标题并注释掉按钮,则标题不会打印。 And if I comment heading then the buttons does not print.
如果我评论标题,那么按钮不会打印。 But together doesn't print anything.
但一起不打印任何东西。 Any suggestion?
有什么建议吗?
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
drumPads : [
{
id: "Q",
src: "https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3",
beat: "Heater-1",
},
{
id: "W",
src: "https://s3.amazonaws.com/freecodecamp/drums/Heater-2.mp3",
beat: "Heater-2"
},
}
handleClick(id, beat) {
return () => {
document.getElementById(id).play();
this.setState({
beatName: beat,
});
};
}
render() {
return (
<Fragment>
<h1>DrumMachine</h1>
<div>
this.state.drumPads.map((button, i) =>
<button key={i} onClick={this.handleClick(button.id, button.beat)}><h1>{ button.id }</h1>
<audio id={button.id} src={button.src} />
</button>
)
</div>
</Fragment>
)
}
}
ReactDOM.render( <App />,
document.getElementById("root")
)
You need to have a single parent element as opposed to <div></div>
followed by another <div></div>
.您需要有一个父元素,而不是
<div></div>
后跟另一个<div></div>
。 You should use a React.Fragment
as the parent element:您应该使用
React.Fragment
作为父元素:
render() {
return (
<>
<h1>Drum Machine</h1>
<div>
//other stuff
</div>
</>
);
}
There were also some syntax errors in the code, namely:代码中还存在一些语法错误,即:
this.state
in constructor this.state
在构造函数中没有右括号map
expression in render()
render()
中的map
表达式周围没有大括号 class App extends React.Component { constructor(props) { super(props); this.state = { drumPads: [ { id: "Q", src: "https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3", beat: "Heater-1" }, { id: "W", src: "https://s3.amazonaws.com/freecodecamp/drums/Heater-2.mp3", beat: "Heater-2" } ] }; } handleClick(id, beat) { return () => { document.getElementById(id).play(); this.setState({ beatName: beat }); }; } render() { return ( <React.Fragment> <h1>DrumMachine</h1> <div> {this.state.drumPads.map((button, i) => <button key={i} onClick={this.handleClick(button.id, button.beat)}> <h1>{button.id}</h1> <audio id={button.id} src={button.src} /> </button> )} </div> </React.Fragment> ); } } ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.