gpt4 book ai didi

javascript - React - 检查元素在 DOM 中是否可见

转载 作者:可可西里 更新时间:2023-11-01 01:24:16 25 4
gpt4 key购买 nike

我正在构建一个表单 - 用户在进入下一个屏幕之前需要回答的一系列问题(单选按钮)。对于字段验证,我使用 yup(npm 包)和 redux 作为状态管理。

对于一个特定的场景/组合,会显示一个新屏幕 (div),要求用户在继续之前进行确认(复选框)。我只想在显示时对此复选框应用验证。

如何使用 React 检查元素 (div) 是否显示在 DOM 中?

我想到的方法是将变量“isScreenVisible”设置为 false,如果满足条件,我会将状态更改为“true”。

我正在检查并在 _renderScreen() 中将“isScreenVisible”设置为 true 或 false,但由于某种原因它会进入无限循环。

我的代码:

class Component extends React.Component {

constructor(props) {
super(props);

this.state = {
formisValid: true,
errors: {},
isScreenVisible: false
}

this.FormValidator = new Validate();
this.FormValidator.setValidationSchema(this.getValidationSchema());
}

areThereErrors(errors) {
var key, er = false;
for(key in errors) {
if(errors[key]) {er = true}
}
return er;
}

getValidationSchema() {
return yup.object().shape({
TravelInsurance: yup.string().min(1).required("Please select an option"),
MobilePhoneInsurance: yup.string().min(1).required("Please select an option"),
Confirmation: yup.string().min(1).required("Please confirm"),
});
}

//values of form fields
getValidationObject() {
let openConfirmation = (this.props.store.Confirmation === true)? 'confirmed': ''

return {
TravelInsurance: this.props.store.TravelInsurance,
MobilePhoneInsurance: this.props.store.MobilePhoneInsurance,
Confirmation: openConfirmation,
}
}

setSubmitErrors(errors) {
this.setState({errors: errors});
}

submitForm() {
var isErrored, prom, scope = this, obj = this.getValidationObject();
prom = this.FormValidator.validateSubmit(obj);

prom.then((errors) => {
isErrored = this.FormValidator.isFormErrored();

scope.setState({errors: errors}, () => {
if (isErrored) {
} else {
this.context.router.push('/Confirm');
}
});
});
}

saveData(e) {
let data = {}
data[e.target.name] = e.target.value

this.props.addData(data)

this.props.addData({
Confirmation: e.target.checked
})
}

_renderScreen = () => {
const {
Confirmation
} = this.props.store

if(typeof(this.props.store.TravelInsurance) !== 'undefined' && typeof(this.props.store.MobilePhoneInsurance) !== 'undefined') &&
((this.props.store.TravelInsurance === 'Yes' && this.props.store.MobilePhoneInsurance === 'No') ||
(this.props.store.TravelInsurance === 'No' && this.props.store.MobilePhoneInsurance === 'Yes')){

this.setState({
isScreenVisible: true
})

return(
<div>
<p>Please confirm that you want to proceed</p>

<CheckboxField
id="Confirmation"
name="Confirmation"
value={Confirmation}
validationMessage={this.state.errors.Confirmation}
label="I confirm that I would like to continue"
defaultChecked={!!Confirmation}
onClick={(e)=> {this.saveData(e)} }
/>
</FormLabel>
</div>
)
}
else{
this.setState({
isScreenVisible: false
})
}
}

render(){
const {
TravelInsurance,
MobilePhoneInsurance
} = this.props.store

return (
<div>
<RadioButtonGroup
id="TravelInsurance"
name="TravelInsurance"
checked={TravelInsurance}
onClick={this.saveData.bind(this)}
options={{
'Yes': 'Yes',
'No': 'No'
}}
validationMessage={(this.state.errors.TravelInsurance) ? this.state.errors.TravelInsurance : null }
/>

<RadioButtonGroup
id="MobilePhoneInsurance"
name="MobilePhoneInsurance"
checked={MobilePhoneInsurance}
onClick={this.saveData.bind(this)}
options={{
'Yes': 'Yes',
'No': 'No'
}}
validationMessage={(this.state.errors.MobilePhoneInsurance) ? this.state.errors.MobilePhoneInsurance : null }
/>

this._renderScreen()

<ButtonRow
primaryProps={{
children: 'Continue',
onClick: e=>{
this.submitForm();
}
}}
</div>
)
}
}

const mapStateToProps = (state) => {
return {
store: state.Insurance,
}
}

const Insurance = connect(mapStateToProps,{addData})(Component)

export default Insurance

最佳答案

这是一个利用 IntersectionObserver 的可重用钩子(Hook)API。

钩子(Hook)

export default function useOnScreen(ref) {

const [isIntersecting, setIntersecting] = useState(false)

const observer = new IntersectionObserver(
([entry]) => setIntersecting(entry.isIntersecting)
)

useEffect(() => {
observer.observe(ref.current)
// Remove the observer as soon as the component is unmounted
return () => { observer.disconnect() }
}, [])

return isIntersecting
}

用法

const DummyComponent = () => {

const ref = useRef()
const isVisible = useOnScreen(ref)

return <div ref={ref}>{isVisible && `Yep, I'm on screen`}</div>
}

关于javascript - React - 检查元素在 DOM 中是否可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45514676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com