use*_*074 3 javascript reactjs
我有一个功能组件,里面有一个按钮。我想在单击该按钮时调用一个功能组件。
当我们点击提交按钮时,预览按钮出现,当用户点击预览按钮时,预览功能组件被调用。
const Form =(props)=>{
handlePreview=(e)=>{
e.preventDefault();
return <Preview/>
}
return(
<input name="email" type="text"/>
<button type="submit" onClick={props.handleSubmit}>Submit</button><br/>
{props.render&&
<button type="submit" onClick={handlePreview}>Preview</button>
}
)
}
Run Code Online (Sandbox Code Playgroud)
当我单击“提交”按钮时,会显示预览按钮,但是当我单击“预览”按钮时,它不会导航到<Preview>功能组件
要渲染组件,您应该从 function 返回它Form。如果您从事件处理程序返回任何组件,它将被忽略。
因此,要显示<Preview/>组件,您应该创建本地状态。在功能组件中,它可以使用React Hooks来完成,如下所示
const Form =(props)=>{
const [isPreviewShown, setPreviewShown] = useState(false);
handlePreview=(e)=>{
e.preventDefault();
setPreviewShown(true); // Here we change state
}
return(
<input name="email" type="text"/>
<button type="submit" onClick={props.handleSubmit}>Submit</button><br/>
{props.render&&
<button type="submit" onClick={handlePreview}>Preview</button>
}
{isPreviewShown && <Preview/>}
)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6852 次 |
| 最近记录: |