我是React的新手,我对某些基本的东西感到困惑.
我需要在呈现DOM之后,在click事件上将组件附加到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>
);
}
};
Run Code Online (Sandbox Code Playgroud)
希望很清楚我需要做什么,希望你能帮我找到合适的解决方案.
Ale*_*lan 88
在使用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>;
Run Code Online (Sandbox Code Playgroud)
Hom*_*ani 14
正如@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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
74635 次 |
| 最近记录: |