gpt4 book ai didi

javascript - onSubmit 方法在使用 Firebase 的 React 中执行渲染

转载 作者:行者123 更新时间:2023-12-02 23:29:11 25 4
gpt4 key购买 nike

我正在尝试在 Firebase FireStore 的集合内设置文档。

我创建了一个组件,它渲染一个带有按钮的 div,然后它有条件地从 open 状态渲染 FormValidation(一个表单)(一个用于在 React 中轻松进行表单验证的模块)。

按钮正在将 open 设置为 true(如果尚未设置为 true)。

然后呈现 formvalidation,它有一个 onsubmit 方法、一个带有 type="submit" 的按钮和一个设置 open 的按钮如果它还不是 false (因此表单验证消失),则为 false。

到目前为止一切都很好,一切都应该工作正常,但由于某种原因,每当我单击按钮显示 formvalition 时,onSubmit 都会运行。

显然,在您按下 type="submit" 按钮之前,它不应该运行

完整代码如下:

import React from 'react'; import { ValidatorForm } from 'react-form-validator-core'; import TextInput from '../TextInput'; import { compose } from 'recompose';

import PlusIcon from '../../resources/icons/add.svg'; import PlusIconBlack from '../../resources/icons/addBlack.svg'; import ArrowIcon from '../../resources/icons/arrowDown.svg'; import BinIcon from '../../resources/icons/rubbishBin.svg';

import ButtonStyles from './button.module.css'; import ListStyles from './list.module.css'; import GameStyles from './game.module.css';

import { withAuthorization } from '../Session'; import { withFirebase } from '../Firebase';

class Games extends React.Component { constructor(props) {
super(props); }

render() {
return(
<div style={{marginBottom: '6em'}}>
<h1 style={{marginTop: '2em'}}>Listas de Videojuegos</h1>
<span style={{display: 'block', width: '100%', height: '2px', background: '#ccc', marginTop: '0.5em'}} />
<ListsContainer />
</div>
); } }

class ListsContainer extends React.Component { constructor(props) {
super(props); }

render() {
return(
<div style={{marginTop: '3em'}}>
<AddButton backgroundColor="#8489C8" icon={PlusIcon} text="Añadir lista" textColor="#fff" type="list" />
<List img="https://i.pinimg.com/originals/30/0e/58/300e58c8416a68dcfcf1761501348243.jpg" backgroundColor="#6168B8" name="Lista 1" games="5" />
<List img="https://i.pinimg.com/originals/30/0e/58/300e58c8416a68dcfcf1761501348243.jpg" backgroundColor="#6168B8" name="Lista 2" games="26" />
<List img="https://i.pinimg.com/originals/30/0e/58/300e58c8416a68dcfcf1761501348243.jpg" backgroundColor="#6168B8" name="Lista 1" games="5" />
</div>
); } }

class List extends React.Component { constructor(props) {
super(props);

this.state = {
open: false,
};

this.openGames = this.openGames.bind(this); }

openGames() {
if(this.state.open === true) {
this.setState({
open: false
});
} else {
this.setState({
open: true
});
} }

render() {
const open = this.state.open;
return(
<div class={ListStyles.list} style={{background: this.props.backgroundColor}}>
<img className={ListStyles.img} src={this.props.img} />
<div className={ListStyles.textBox}>
<h2>{this.props.name}</h2>
<span><b>{this.props.games}</b> Juegos</span>
</div>
<button className={open ? ListStyles.collapseUp : ListStyles.collapse} onClick={this.openGames}><img src={ArrowIcon} alt="" /></button>
<button className={ListStyles.bin} onClick={this.openGames}><img src={BinIcon} alt="" /></button>
<div style={{marginTop: '3em'}} className={open ? ListStyles.games : ListStyles.gamesNotOpen}>
<Game name="League Of Legends" platform="PC" hours="2000" />
<Game name="Borderlands" platform="XBOX 360" hours="50" />
<span style={{display: 'block', height: '1em'}} />
<AddButton backgroundColor="#fff" icon={PlusIconBlack} text="Añadir juego" textColor="#363636" type="game" />
</div>
</div>
); } }

class Game extends React.Component { constructor(props) {
super(props); }

render() {
return(
<div class={GameStyles.gameBox}>
<h3>{this.props.name}</h3>
<span><b>{this.props.hours}</b> Horas jugadas</span>
<span><b>{this.props.platform}</b></span>
<button className={GameStyles.bin} ><img src={BinIcon} alt="" /></button>
</div>
); } }

class AddButtonBase extends React.Component { constructor(props) {
super(props);

this.state = {
open: false,
listName: '',
imgUrl: '',
gameName: '',
platform: '',
hours: ''
};

this.openForm = this.openForm.bind(this);
this.closeForm = this.closeForm.bind(this);
this.openFormList = this.openFormList.bind(this);
this.openFormGame = this.openFormGame.bind(this); }

submitList = (authUser) => {
console.log(authUser)
const { listName, imgUrl } = this.state;

this.props.firebase.list(listName, JSON.parse(authUser).uid).set(
{
imgUrl,
},
{ merge: true },
).then(() => this.closeList())
.catch(error => console.log(error.message)); }

submitGame = event => {
//const { gameName, platform, hours } = this.state;

console.log("SASNJKAB") }

handleChangeList = event => {
this.setState({ [event.target.name]: event.target.value }); };

handleChangeGame = event => {
this.setState({ [event.target.name]: event.target.value }); };

openForm() {
if(this.state.open === false) {
this.setState({
open: true
});
} }

closeForm() {
if(this.state.open === true) {
this.setState({
open: false
});
} }

openFormList = () => (
<ValidatorForm className={ButtonStyles.formList} ref="loginForm" onSubmit={this.submitList(localStorage.getItem("authUser"))}>
<h3>Añadir Lista</h3>
<span style={{display: 'block', width: '100%', height: '2px', background: '#fff', marginTop: '0.5em', marginBottom: '1.5em'}} />
<TextInput
style={{width: '26em'}}
type="text"
name="listName"
title="Nombre de la lista"
onChange={this.handleChangeList}
value={this.state.listName}
validators={['required', 'maxStringLength:20']}
errorMessages={['Campo obligatorio', 'Se ha excedido el límite de caracteres']} /><br />
<TextInput
style={{width: '26em'}}
type="text"
name="imgUrl"
title="Url para el icono de la lista"
onChange={this.handleChangeList}
value={this.state.imgUrl}
validators={['required']}
errorMessages={['Campo obligatorio']} /><br />
<div style={{textAlign: 'right'}}>
<button type="submit" className={ButtonStyles.createList}>Crear nueva lista</button>
<button className={ButtonStyles.closeList} onClick={this.closeForm}>Cerrar</button>
</div>
</ValidatorForm> )

openFormGame = () => (
<ValidatorForm className={ButtonStyles.formGame} ref="loginForm" onSubmit={this.submitGame()}>
<h3>Añadir Juego</h3>
<span style={{display: 'block', width: '100%', height: '2px', background: '#fff', marginTop: '0.5em', marginBottom: '1.5em'}} />
<TextInput
style={{width: '26em'}}
type="text"
name="gameName"
title="Nombre del videojuego"
onChange={this.handleChangeList}
value={this.state.gameName}
validators={['required', 'maxStringLength:20']}
errorMessages={['Campo obligatorio', 'Se ha excedido el límite de caracteres']} /><br />
<TextInput
style={{width: '26em'}}
type="text"
name="platform"
title="Plataforma"
onChange={this.handleChangeList}
value={this.state.platform}
validators={['required', 'maxStringLength:10']}
errorMessages={['Campo obligatorio', 'Se ha excedido el límite de caracteres']} /><br />
<TextInput
style={{width: '26em'}}
type="text"
name="hours"
title="Horas jugadas"
onChange={this.handleChangeList}
value={this.state.hours}
validators={['required', 'isNumber']}
errorMessages={['Campo obligatorio', 'Este campo sólo admite números']} /><br />
<div style={{textAlign: 'right'}}>
<button type="submit" className={ButtonStyles.createGame}>Crear nueva lista</button>
<button className={ButtonStyles.closeGame} onClick={this.closeForm}>Cerrar</button>
</div>
</ValidatorForm> )

render() {
return(
<div>
<button onClick={this.openForm} className={ButtonStyles.button} style={{ background: this.props.backgroundColor, color: this.props.textColor }}><img src={this.props.icon} /> <span>{this.props.text}</span></button>
{
(this.state.open && (this.props.type === "list")) ? this.openFormList() : null
}
{
this.state.open && this.props.type === "game" ? this.openFormGame() : null
}
</div>
); } }

const AddButton = withFirebase(AddButtonBase);

const condition = authUser => !!authUser;

export default withAuthorization(condition)(Games);

最佳答案

我认为您的问题是,当您将提交方法分配为回调时,您正在调用它们。

您在括号内调用此方法:

onSubmit={this.submitList(localStorage.getItem("authUser"))}

这里也是:

onSubmit={this.submitGame()}

与您的 onclick 处理程序进行比较:

onClick={this.closeForm}

有几种方法可以解决这个问题,例如删除调用括号,或者将它们包装在匿名函数/闭包中,例如:

onSubmit={()=> this.submitList(localStorage.getItem("authUser"))}

关于javascript - onSubmit 方法在使用 Firebase 的 React 中执行渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56588959/

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