【发布时间】:2019-12-10 15:16:53
【问题描述】:
我是新手,我不明白为什么 h1 标签内的 title 会更新,但 Image 组件内的 url 却没有?
上市组件
import React, { useState, useEffect, useContext } from 'react';
import Image from './Image';
import Size from '../index';
export default function Listing(props) {
const [title, setTitle] = useState(props.title);
const [url, setUrl] = useState(props.url);
const value = useContext(Size);
return (
<div>
<Image url={url} size={value.size} />
<h1>{title}</h1>
<form>
<input id='URL' type='text' />
<button
onClick={e => {
e.preventDefault();
setUrl(document.getElementById('URL').value);
setTitle(document.getElementById('URL').value);
}}
>
Submit
</button>
</form>
</div>
);
}
到目前为止,我的猜测是,如果 prop 更改,React 不会更新子组件,但是我该如何手动更新呢?
图像组件
import React from 'react';
export default class Image extends React.Component {
//console.log(props.size);
constructor(props) {
super(props);
this.url = props.url;
this.size = props.size;
}
render() {
return <img src={this.url} style={{ height: this.size + 'px' }} alt='' />;
}
}```
【问题讨论】:
-
能否贴出Image组件代码?
-
不要混合使用 DOM 操作和 React,use React events to keep the input state in sync。
-
@MassimilianoSartoretto 已编辑
-
请参考reactjs.org/docs/forms.html来处理表单中的值
-
在你的
Image组件中,在render函数中使用this.props,否则当值改变时它永远不会更新。
标签: javascript reactjs jsx