请问如何在ReactJs中执行此操作。你可以直接在反应中操纵dom,或者有一种操作dom的反应方式。我在网上搜索,但仍无法找到正确的信息。感谢
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var x = document.createElement("INPUT");
x.setAttribute("type", "text");
x.setAttribute("value", "Hello World!");
document.body.appendChild(x);
}
</script>
答案 0 :(得分:0)
FirebaseMessaging.getInstance().subscribeToTopic("Topic3");
class App extends React.Component{
constructor(props){
super(props);
this.state = {input: []}
this.addItem = this.addItem.bind(this)
}
addItem(){
const input = this.state.input;
const item = <input type="text" value="Hello World!" />
this.setState({input : input.concat(item)})
}
render(){
return(
<div>
{this.state.input}
<br/>
<button onClick={this.addItem}>Try it</button>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById("container"));
答案 1 :(得分:0)
React有一个名为React.createElement
的api,您可以使用它来创建元素
class App extends React.Component {
constructor() {
super();
this.state = {
elements: []
};
}
createNew = () =>{
const newEle = {'element': 'input', "defaultValue": "Hello World!"}
this.setState(prevstate=> ({elements: [...prevstate.elements, newEle]}));
}
render() {
return (
<div>
<button onClick={() => this.createNew()}>Try it</button>
{this.state.elements.map(({element, ...rest}) => React.createElement(element, {...rest}))}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>