我想访问设置为子组件状态的对象,并将其传递给其同级组件:
function TextDetection({ textToParent }) {
const [data, setData] = useState([])
const uploadImage = async (image) => {
var formData = new FormData();
formData.append('photo', image[0])
const response = await fetch('/upload', {
method: "post",
body: formData
})
const body = await response.json();
setData(body.split(/\r?\n/))
textToParent(data)
}
return (
<Grid container className="App" direction="column" alignItems="stretch">
<Container id="dropzoneContainer">
<Card variant="outlined">
<Dropzone uploadImage = {uploadImage}/>
</Card>
</Container>
</Grid>
);
}
目的是让同级组件可以使用此转录。正如您在下面的代码片段中看到的,我当前正在通过 props 向子级传递回调来访问子级的状态。
export default function App() {
const [text, setText] = useState([])
function handleChange(newText) {
setText(newText)
}
return (
<div>
<Grid item xs={12} sm={4}>
<TextDetection textToParent={handleChange}/>
</Grid>
<Grid item xs={12} sm={8}>
<TextTable segments={text}/>
</Grid>
</div>
);
}
向子级传递回调以访问其状态与“提升状态”的概念不符。 鉴于 TextDetection 子级接收设置为状态的对象,在这种情况下是否有应用该原则的方法?
TextDetection
组件应该处理与OCR相关的所有事情,其中包括解析文本。但是,它不应该有本地状态。解析完成后,它应该调用
textToParent
。function TextDetection({ textToParent }) {
const uploadImage = async (image) => {
var formData = new FormData();
formData.append('photo', image[0])
const response = await fetch('/upload', {
method: "post",
body: formData
})
const body = await response.json();
textToParent(body.split(/\r?\n/));
}
return (
<Grid container className="App" direction="column" alignItems="stretch">
<Container id="dropzoneContainer">
<Card variant="outlined">
<Dropzone uploadImage = {uploadImage}/>
</Card>
</Container>
</Grid>
);
}
父级应该保存由
TextDetection
创建的状态,并将其提供给
TextTable
(以及任何其他需要它的子级)。export default function App() {
const [text, setText] = useState([])
return (
<div>
<Grid item xs={12} sm={4}>
<TextDetection textToParent={setText}/>
</Grid>
<Grid item xs={12} sm={8}>
<TextTable segments={text}/>
</Grid>
</div>
);
}
data
。在这种情况下,您可以在父组件中运行函数
function TextDetection({ textToParent }) {
return (
<Grid container className="App" direction="column" alignItems="stretch">
<Container id="dropzoneContainer">
<Card variant="outlined">
<Dropzone uploadImage = {textToParent}/>
</Card>
</Container>
</Grid>
);
}
家长:
export default function App() {
const [text, setText] = useState([])
function handleChange(newText) {
var formData = new FormData();
formData.append('photo', image[0])
const response = await fetch('/upload', {
method: "post",
body: formData
})
const body = await response.json();
setText(body.split(/\r?\n/))
}
return (
<div>
<Grid item xs={12} sm={4}>
<TextDetection textToParent={handleChange}/>
</Grid>
<Grid item xs={12} sm={8}>
<TextTable segments={text}/>
</Grid>
</div>
);
}
注意:这是概念,未经测试。