react修改页面dom的两种办法
一:使用选择器:
1、引入react-dom
import ReactDom from 'react-dom'
2、给react节点设置id或类名等标识
<span id='tip'></span>
3、定义变量保存dom元素
const span=document.getElementById('tip')
4、通过ReactDom的findDOMNode()方法修改dom的属性
ReactDom.findDOMNode(span).style.color='red'
点击时: e.currentTarget 获取到点击的dom,通过改变样式或者innerHtml改变dom
二:使用ref属性
1、给指定标签设置ref属性
<span ref='tip'></span>
2、通过this.refs.ref属性值来修改标签的属性
this.refs.tip.style.color = "red"
class组件
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef(); }
render() {
return <div ref={this.myRef} />; }
}
函数组件使用
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` 指向已挂载到 DOM 上的文本输入元素
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}