我是React的新手,我对某种基本的东西感到困惑。
在呈现DOM之后,我需要在点击事件上将组件附加到DOM。
我最初的尝试如下,但它不起作用。但这是我认为最好的尝试。 (事先道歉,将jQuery与React混合使用。)
ParentComponent = class ParentComponent extends React.Component {
constructor () {
this.addChild = this.addChild.bind(this);
}
addChild (event) {
event.preventDefault();
$("#children-pane").append(<ChildComponent/>);
}
render () {
return (
<div className="card calculator">
<p><a href="#" onClick={this.addChild}>Add Another Child Component</a></p>
<div id="children-pane">
<ChildComponent/>
</div>
</div>
);
}
};
希望我能清楚我需要做什么,希望你能帮助我找到合适的解决方案。
答案 0 :(得分:75)
当您使用React时,不要使用jQuery来操作DOM。 React组件应该呈现表示它们在给定某个状态时应该是什么样子;转化为什么的DOM由React自己处理。
您要做的是将“确定要渲染的内容的状态”存储在链的上方,然后将其传递下去。如果您要渲染n
个孩子,那么该状态应该由包含您组件的任何内容“拥有”。例如:
class AppComponent extends React.Component {
state = {
numChildren: 0
}
render () {
const children = [];
for (var i = 0; i < this.state.numChildren; i += 1) {
children.push(<ChildComponent key={i} number={i} />);
};
return (
<ParentComponent addChild={this.onAddChild}>
{children}
</ParentComponent>
);
}
onAddChild = () => {
this.setState({
numChildren: this.state.numChildren + 1
});
}
}
const ParentComponent = props => (
<div className="card calculator">
<p><a href="#" onClick={props.addChild}>Add Another Child Component</a></p>
<div id="children-pane">
{props.children}
</div>
</div>
);
const ChildComponent = props => <div>{"I am child " + props.number}</div>;
答案 1 :(得分:10)
正如@Alex McMillan所提到的,使用state来决定dom中应该呈现的内容。
在下面的示例中,我有一个输入字段,我想在用户单击按钮时添加第二个字段,onClick事件处理程序调用handleAddSecondInput(),它将inputLinkClicked更改为true。我正在使用三元运算符来检查truthy状态,它呈现第二个输入字段
class HealthConditions extends React.Component {
constructor(props) {
super(props);
this.state = {
inputLinkClicked: false
}
}
handleAddSecondInput() {
this.setState({
inputLinkClicked: true
})
}
render() {
return(
<main id="wrapper" className="" data-reset-cookie-tab>
<div id="content" role="main">
<div className="inner-block">
<H1Heading title="Tell us about any disabilities, illnesses or ongoing conditions"/>
<InputField label="Name of condition"
InputType="text"
InputId="id-condition"
InputName="condition"
/>
{
this.state.inputLinkClicked?
<InputField label=""
InputType="text"
InputId="id-condition2"
InputName="condition2"
/>
:
<div></div>
}
<button
type="button"
className="make-button-link"
data-add-button=""
href="#"
onClick={this.handleAddSecondInput}
>
Add a condition
</button>
<FormButton buttonLabel="Next"
handleSubmit={this.handleSubmit}
linkto={
this.state.illnessOrDisability === 'true' ?
"/404"
:
"/add-your-details"
}
/>
<BackLink backLink="/add-your-details" />
</div>
</div>
</main>
);
}
}