我有演示文稿和容器组件。表示组件使用本地状态。我想删除父组件的本地状态。这是必需的,以便演示组件没有逻辑。请帮助我
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);
答案 0 :(得分:0)
如果我正确理解了您的问题/问题,您只是想从Page1
中删除本地组件状态,并从redux中传递该状态。
onChange
处理程序,稍后您将访问当前值。presentText
。useRef
react钩子并声明textareaRef
常量,因为在渲染过程中它没有重新分配。第1页
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>
);
}