[英]How can I make a JavaScript (with React framework) button create a new instance of a class?
I am new to web development and I only now make my first page (using ReactJS on top of it), so sorry if this is a noob question.我是 Web 开发的新手,我现在才制作我的第一页(在它上面使用 ReactJS),如果这是一个菜鸟问题,很抱歉。 In my page I have created 3 windows which are going to be filled with information later on, and I want the user to be able to make their own ones by clicking a "+" button.
在我的页面中,我创建了 3 个稍后将填充信息的窗口,我希望用户能够通过单击“+”按钮来创建自己的窗口。 Though, for some reason, my code does not work.
但是,由于某种原因,我的代码不起作用。 Even after one clicks at the "+" button, nothing happens.
即使单击“+”按钮后,也没有任何反应。 Here's the code of my 'Board' class for demonstration.
这是我用于演示的“Board”类的代码。
class Board extends React.Component {
renderWindow(i) {
return (
<Window name={i} />
);
}
handleClick() {
var test = document.createElement("P");
test.innerHTML = "this.renderWindow('test-thingy')";
document.body.appendChild(test);
}
render() {
return (
<div>
<div className="info-window">
{this.renderWindow("Contacts")}
{this.renderWindow("Accounts")}
{this.renderWindow("Info")}
</div>
<button
className="button1"
onClick={() => this.handleClick()}
>
{"+"}
</button>
</div>
);
}
}
I just don't know how to make it respond accordingly, because right now it only creates a text with the quote from test.innerHTML.我只是不知道如何让它做出相应的响应,因为现在它只创建一个带有 test.innerHTML 引用的文本。 I have tried several other syntaxes for that line, such as:
我为该行尝试了其他几种语法,例如:
test.innerHTML = "{this.renderWindow('test-thingy')}";
or或者
test.innerHTML = "<div> {this.renderWindow('test-thingy')} </div>";
or even inverting the " and '. I have been searching ever since for a way, but I am unable to find it. I want it to create a fourth window with the name 'test-thingy'.甚至反转“和”。从那以后我一直在寻找一种方法,但我无法找到它。我希望它创建一个名为“test-thingy”的第四个窗口。
You should put the JSX element to be rendered due to change state as part of the render
method .您应该将 JSX 元素作为
render
方法的一部分,因为更改状态而被render
。
const WindowComp = ({ name }) => <p>{name}</p>; class Board extends React.Component { state = { windowNames: ['Contacts', 'Accounts', 'Info'] }; handleClick() { this.setState({ windowNames: [...this.state.windowNames, 'test-thingy'] }); } render() { return ( <div> <div className="info-window"> {this.state.windowNames.map( (name, i) => <WindowComp key={i} name={name} /> )} </div> <button className="button1" onClick={() => this.handleClick()} > {"+"} </button> </div> ); } } ReactDOM.render(<Board />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div class="react"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.