gpt4 book ai didi

javascript - 在父组件 React 中显示按钮信息

转载 作者:行者123 更新时间:2023-12-02 21:07:56 27 4
gpt4 key购买 nike

我有一个 react 类,其中有一个 id="display"的 div。我需要这个 div 在单击该按钮时显示与该按钮关联的名称。

这是我的代码:

import React from "react";
import ReactDom from "react-dom";

const sounds = [
{
idnum: "1",
id: "Q",
src: "https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3",
name: "Hello",
},
{
idnum: "2",
id: "W",
src: "https://s3.amazonaws.com/freecodecamp/drums/Heater-2.mp3",
name: "Hello",
},
{
idnum: "3",
id: "E",
src: "https://s3.amazonaws.com/freecodecamp/drums/Heater-3.mp3",
name: "Hello",
},
{
idnum: "4",
id: "A",
src: "https://s3.amazonaws.com/freecodecamp/drums/Heater-4_1.mp3",
name: "Hello",
},
{
idnum: "5",
id: "S",
src: "https://s3.amazonaws.com/freecodecamp/drums/Heater-6.mp3",
name: "Hello",
},
{
idnum: "6",
id: "D",
src: "https://s3.amazonaws.com/freecodecamp/drums/Dsc_Oh.mp3",
name: "Hello",
},
{
idnum: "7",
id: "Z",
src: "https://s3.amazonaws.com/freecodecamp/drums/Kick_n_Hat.mp3",
name: "Hello",
},
{
idnum: "8",
id: "X",
src: "https://s3.amazonaws.com/freecodecamp/drums/RP4_KICK_1.mp3",
name: "Hello",
},
{
idnum: "9",
id: "C",
src: "https://s3.amazonaws.com/freecodecamp/drums/Cev_H2.mp3",
name: "Hello",
},
];

var dispName = "NONE";

class SoundButton extends React.Component {
constructor(props) {
super(props);
this.state = {
audioSource: "not clicked",
};
this.soundOn = this.soundOn.bind(this);
}

buttonRef = React.createRef();
audioRef = React.createRef();

componentDidMount() {
document.addEventListener("keypress", this.buttonPress);
}

buttonPress(e) {
var a = e.key.toUpperCase();
if (
a == "Q" ||
a == "W" ||
a == "E" ||
a == "A" ||
a == "S" ||
a == "D" ||
a == "Z" ||
a == "X" ||
a == "C"
) {
console.log(a);
document.getElementById(a).click();
}
}

soundOn() {
console.log(this.audioRef.current);
document.getElementById(this.props.keyTrigger);
console.log(this.props);
this.audioRef.current.play();
this.dispName = "DISPLAY";
}



render() {
const { info } = this.props;

return (
<button
ref={this.buttonRef}
className="drum-pad"
id={info["idnum"]}
onClick={this.soundOn}
>
{info["id"]}
<audio
ref={this.audioRef}
src={info.src}
className="clip"
id={info.id}
type="audio/mp3"
></audio>
</button>
);
}
}

class Button extends React.Component {
// any other logic
constructor() {
super();
}

render() {
const buttonList = sounds.map((info) => (
<SoundButton info={info} key={info.id} />
));
return (
<div id="display">
{dispName}
<div>{buttonList}</div>
</div>
);
}
}
export default Button;

所以在这里,我有我的 const dispName,单击时它应该更新为按钮名称。按钮的名称存储在sounds.name中。

请在这里帮助我。

谢谢!

最佳答案

您需要管理 Button 组件中的状态变量,然后将回调传递给 SoundButton 组件,单击按钮时将使用按钮名称调用该回调。这是工作示例的链接: https://codesandbox.io/s/react-filepond-live-demo-7v3v9?file=/src/index.js

希望它能解决您的问题:)

关于javascript - 在父组件 React 中显示按钮信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61177209/

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