javascript - 追加新的 React 组件 onclick
问题描述
我对 React 比较陌生,但熟悉 JavaScript。我想制作一个非常简单的应用程序,每当我想附加一个新的 HTML 元素时,我都会使用 JavaScript 做这样的事情:
document.getElementById("root").innerHTML += "<h1>Title</h1>";
. 在 React 中,我想在单击按钮时将一个新的 MyComponent 组件附加到我的页面。我怎样才能以类似的方式做到这一点.innerHTML +=
。以下是我到目前为止给出的想法,但它不起作用。
index.js:
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
应用程序.js:
function my_func() {
var prop1 = prompt("Input here ");
var prop2 = "new_id";
document.getElementById("app-root").innerHTML += <MyComponent p1={ prop1 } p2={ prop2 }/>;
}
function App() {
return (
<div id="app-root">
<Button color="primary" onClick={ my_func }>Add</Button>{' '}
</div>
);
}
export default App;
解决方案
你应该在这里实现 React State。您将添加的组件列表保存到 this.state。这是我的建议。
这是 App.js
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
clicked: false,
mycomponentlist:[]
};
this.my_func = this.my_func.bind(this);
}
my_func(){
let {mycomponentlist} = this.state;
var prop1 = prompt("Input here ");
var prop2 = "new_id";
mycomponentlist.push({prop1,prop2});
this.setState({mycomponentlist,clicked:true});
}
render() {
const {clicked,mycomponentlist} = this.state;
return (
<div id="app-root">
<button onClick={this.my_func }>Add</button>
{clicked&& mycomponentlist.map(mycomponent=> <MyComponent p1={ mycomponent.prop1 } p2={ mycomponent.prop2 }/>)}
</div>
);
}
}
export default App;
这是 MyComponent.js
import React, { Component } from 'react';
class MyComponent extends Component {
render() {
const { p1,p2} = this.props;
return (
<div >
//you can use p1,p2 here...
<p>{p1}</p>
<p>{p2}</p>
</div>
)
}
}
export default MyComponent;
我相信这会奏效。当第一次单击按钮时,单击状态变为真,因此每次渲染都会显示组件数组。
推荐阅读
- sql - CSV 到 SQL 导入会随意重新排序 CSV 数据 为什么?
- python - 不平衡数据集的分类步骤是什么?
- java - 如何将对象链接到某个字典/查找表?
- python - 从两个 daya 框架中删除匹配的元素并打印不匹配的元素
- css - 如何通过 Selenium WebDriver 处理下载、分享和删除图标?
- react-native - 图像未显示或覆盖 react-native-element 卡片组件中视图的整个可用区域
- javascript - 如何在div中显示按键
- c - 从 +ENA 和 -ENA 引脚启用和禁用步进电机驱动器的正确方法是什么?
- r - 根据 r 中另一个数据框中的列组合选择数据框中的特定行
- c - Printf 格式字符串问题(PW.BAD_PRINTF_FORMAT_STRING)