我有表示和容器组件。演示组件使用本地状态。我想删除父组件的本地状态。这是必要的,这样表示组件就没有逻辑了。请帮我
Page1.jsx:
import React, { useState } from 'react';
function Page1(props) {
let textareaRef = React.createRef();
const [state, setState] = useState({
presentText: '',
});
function textareaSet() {
props.setAppTextCreator(textareaRef.current.value);
textareaRef.current.value = '';
}
function textareaChange() {
setState({...state, presentText: textareaRef.current.value})
}
return (
<div>
<textarea
ref={ textareaRef }
onChange={ textareaChange }>
</textarea>
<button onClick={ textareaSet }>send</button>
<div>present: { state.presentText }</div>
<div>memorized: { props.text }</div>
</div>
);
}
export default Page1;
Page1smart.jsx:
import {connect} from "react-redux";
import { setAppTextCreator } from '../../redux/appReducer';
import Page1 from './Page1';
const mapStateToProps = state => {
return {
text: state.appReducer.appText,
presentText: state.presentText
}
}
export default connect(mapStateToProps, { setAppTextCreator })(Page1);
如果我正确理解您的问题,您只是想从Page1
中删除本地组件状态,并从redux中传入该状态。
- 删除文本区域
onChange
处理程序,您稍后将访问当前值 - 渲染从道具传递的
presentText
- 使用
useRef
react钩子并声明textareaRef
常量,因为它在渲染过程中没有重新分配
Page1
import React, { useRef, useState } from 'react';
function Page1({ presentText, setAppTextCreator, text }) {
const textareaRef = useRef();
function textareaSet() {
setAppTextCreator(textareaRef.current.value);
textareaRef.current.value = '';
}
return (
<div>
<textarea ref={textareaRef} />
<button onClick={textareaSet}>send</button>
<div>present: {presentText}</div>
<div>memorized: {text}</div>
</div>
);
}