我想根据Click按钮传递的值动态更改表单的标题。例如:我的表格标题是Book Health Care Services
。每当我导航到表格时,我都想将表格的标题更改为Book Doctor Consult Services
。点击按钮我想更改表格的标题。
按钮位于组件A&表格标题位于组件B中。
我怎样才能做到这一点。有人能帮帮我吗。
您可以使用以下结构:
import { useState } from "react";
// you need a mother component for passing variables from component A to B
export default function MotherOfAAndB(props) {
// changing variables need to be stored in state variables, this is a
// React pattern
const [formTitle, setFormTitle] = useState("");
// by using this function in the mother component and passing it with
// props to the component A, you can pass formTitle from component A to
// mother component, this is a React pattern, and then you can pass it
// to component B as props
function onChangeFormTitle(formTitle) {
// changing state varibale "formTitle" for passing it through props
// to component B
setFormTitle(formTitle)
}
return <>
<A
// passing function "onChangeFormTitle" through props to
// component A, provides ability to pass vairables from inside
// of component A to mother component for any other uses
onChangeFormTitle={onChangeFormTitle}
/>
<B
// passing "formTitle" variable to component B, the main pupose
// of previous efforts
formTitle={formTitle}
/>
</>
}
// component A could be either in separate file (using import at the top of
// this file) or in current file (no need to import)
function A(props) {
// we need state variables for changing values, this is a React pattern
const [formTitleInComponentA, setFormTitleInComponentA] = useState("");
// handle changing of input value
function onChange(e) {
// changing state variable "formTitleInComponentA"
setFormTitleInComponentA(e.target.value)
}
return <>
<input
type="text"
onChange={onChange}
// setting value={formTitleInComponentA} is needed otherwise you
// can't set the value of input variables in state variables for
// other usages, this is a React pattern
value={formTitleInComponentA}
/>
<button
// passing "formTitleInComponentA" to "props.onChangeFormTitle",
// cause to change state variable "formTitle" in mother
// component
onClick={() => props.onChangeFormTitle(formTitleInComponentA)}
/>
</>
}
// component A could be either in separate file (using import at the top of
// this file) or in current file (no need to import)
function B(props) {
// any usage of variable "formTitle"
return <>{props.formTitle}</>
}
UPDATE如果将props.onChangeFormTitle(formTitleInComponentA)
放置在组件A
的onChange(e)
中,则在组件B
中提供formTitle的实时更改