我正在动态创建很多元素。我有一个状态数组,记录元素。随着我添加更多元素,它们与之前的数组元素相连。这是代码。
var App = React.createClass({
getInitialState: function() {
return {
propsList: []
};
},
addProps: function(props) {
var propsList = this.state.propsList.concat([props]);
this.setState({ propsList: propsList });
},
render: function() {
var components = this.state.propsList.map(function(props) {
return React.createElement('g', props);
});
return React.createElement('div', null, components);
}
});
ReactDOM.render(
React.createElement(App, null),
document.getElementById('svg')
);
我想删除执行了点击操作的元素(g
标记)。我曾尝试使用refs,但它不起作用,因为数组存储太多元素。
答案 0 :(得分:3)
请注意,如果"用户操作"发生在你的React组件之外(即app中的其他地方)。如果"用户操作"作为React组件中的事件发生,您只需调用一次渲染,而App会将节点保持为状态,并且只调用this.setState({node:modifiedNodes});更改状态,这将导致React更新您的DOM。
var App = React.createClass({
render: function() {
// Get the node from the passed-in props
var node = this.props.node;
// generate the child components
var components = node.map(function(props) {
return React.createElement('g', {
id: props.id,
key: props.id
},
React.createElement('path', props));
});
// render them in a div
return React.createElement('div', null, components);
}
});
// first time it will create the DOM
// after that it just modifies the DOM
function renderApp(node, element) {
ReactDOM.render(React.createElement(App, {
node: node
}), element);
}
// Call when you want to get rid of the App completely
// and cleanup memory without reloading the page
function destroyApp(element) {
ReactDOM.unmountComponentAtNode(element);
}
// Initial render
var node = Interfaces.Embroidery.node;
renderApp(node, document.getElementById('parentDrawingNode'));
function updateNodeOnSomeUserActionThatHappensOutsideOfReact(...) {
node.push(...); // or whatever modification you want
// re-render
renderApp(node, document.getElementById('parentDrawingNode'));
}
答案 1 :(得分:1)
我是根据穆罕默德的回答做到的。 这是我的代码。
var Counter = React.createClass({
incrementCount(){
this.setState({
count: this.state.count + 1,
count2:this.state.count2 -1
});
this.classCss = "asdfadsf";
},
getInitialState(){
return {
count: 0,
count2:8999
}
},
tick(classNameReact) {
//<HelloWorld date={new Date()} />
ReactDOM.render(
React.createElement(classNameReact,{date:new Date()}),
document.getElementById('mount-point2')
);
},
render: function(){
this.classCss ="lala";
return (
<div className={this.classCss}>
<h1>Count: {this.state.count}</h1>
<h1>Count2: {this.state.count2}</h1>
<button type="button" onClick={this.incrementCount}>Increment</button>
<button type="button" onClick={()=>this.tick(HelloWorld)}>TICK</button>
<button type="button" onClick={()=>this.tick(Counter)}>TICK</button>
<div id="mount-point2"></div>
</div>
);
}
});
class HelloWorld extends React.Component {
render() {
return (
<p>
Hello, <input type="text" placeholder="Your name here" />!
It is {this.props.date.toTimeString()}
</p>
);
}
}