gpt4 book ai didi

javascript - 提交后 React.js "hide element and reveal next element"

转载 作者:行者123 更新时间:2023-12-03 03:45:43 25 4
gpt4 key购买 nike

我正在开发一款 Mad Libs 游戏,向用户提出如下问题:

Enter a Noun

用户填写正确的名称,点击提交,然后该文本输入现在被隐藏并显示下一个问题。

我知道它处理条件渲染以使其正常工作,但我不确定如何以及从哪里开始。我写了一个用户故事,试图在写的时候跟进,但仍然有点迷失。我的用户故事是

When user enters in text and hits submit (or the enter key) then the text input is hidden (but not deleted or removed because the value entered is used to pass props) and the next text input with a new input is revealed until. When all questions are answered, the Madlibs component is called.

除了上面的用户故事之外,一切都已构建完毕并正常运行。我现在没有收到错误,我只是不知道如何为此编写条件函数。

这是我的代码:

import React, { Component } from 'react';
import styled from 'styled-components';
import Crawler from './crawler';

const NextQuestion = styled.div`
position: absolute;
color: white;
display: block;
margin-top: 108px;
`;

class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {
value1: 'enter proper name',
value2: 'noun',
value3: 'enter another proper name',
newValue: '',
submitted: false,
input1: 0,
input2: 0,
input3: 0,
input4: 0,
input5: 0,
input6: 0,
input7: 0
};

this.handleFirstChange = event => this.handleChange(event, 'value1');
this.handleSecondChange = event => this.handleChange(event, 'value2');
this.handleThirdChange = event => this.handleChange(event, 'value3');
this.handleFourthChange = event => this.handleChange(event, 'value4');
this.handleFifthChange = event => this.handleChange(event, 'value5');
this.handleSixthChange = event => this.handleChange(event, 'value6');
this.handleSeventhChange = event => this.handleChange(event, 'value7');
this.handleSubmit = event => this._handleSubmit(event);
}

handleChange(event, type) {
let newState = {};
newState[type] = event.target.value;
this.setState(newState);
}

_handleSubmit(event) {
event.preventDefault();
let toggle = this.state.visable;
this.setState({ visable: !toggle });
}

render() {
const divStyle = {
marginTop: '50px',
color: 'white',
top: '25px',
position: 'absolute'
};
let question = null;
const show = this.state.visable;
if (show) {
question = (
<div>
<Crawler
properName1={this.state.value1}
noun1={this.state.value2}
properName2={this.state.value3}
properName3={this.state.value4}
noun2={this.state.value5}
personsName1={this.state.value6}
noun3={this.state.value7}
/>
</div>
);
}
return (
<div>
<div style={divStyle}>
<form onSubmit={this.handleSubmit}>
<label>
Proper Name:
<input
name="input1"
type="text"
value={this.state.value1}
onChange={this.handleFirstChange}
/>
</label>
<label>
Noun:
<input
name="input2"
type="text"
value={this.state.value2}
onChange={this.handleSecondChange}
/>
</label>
<label>
Another Proper Name:
<input
name="input3"
type="text"
value={this.state.value3}
onChange={this.handleThirdChange}
/>
</label>
<label>
And Another Proper Name:
<input
name="input4"
type="text"
value={this.state.value4}
onChange={this.handleFourthChange}
/>
</label>
<label>
Noun:
<input
name="input5"
type="text"
value={this.state.value5}
onChange={this.handleFifthChange}
/>
</label>
<label>
Person's Name:
<input
name="input6"
type="text"
value={this.state.value6}
onChange={this.handleSixthChange}
/>
</label>
<label>
Another Noun:
<input
name="input7"
type="text"
value={this.state.value7}
onChange={this.handleSeventhChange}
/>
</label>
<input type="submit" value="Submit" />
</form>
</div>
<NextQuestion>
{question}
</NextQuestion>
</div>
);
}
}

export default NameForm;

我使用这个练习来教我更多关于 React 和条件的知识。感谢您的帮助。

最佳答案

问题列表

首先您需要创建一个问题列表:数组

const QuestionsList = [
{
// Your question title
q: "Are you a human?",

// Validate the user answer
a: (answer) => (answer === 'yes'),

// Force user to give a correct answer
required: true

// Add more properties
...
},
...
];

您可以通过设置数组的索引来浏览问题:

this.state = { current: 0 }
...

// Select current question
QuestionList[this.state.current]

// Select next question
QuestionList[this.state.current + 1]

// Select last question
QuestionList[QuestionList.length - 1]

问题组件

When user enters in text and hits submit then the text input is hidden (but not deleted or removed because the value entered is used to pass props) and the next text input with a new input is revealed until.

由于您仅使用输入[text],因此您可以使用单个组件来解决所有问题,
无需在此处处理条件:

    const RenderQuestion = (
<div>
<h2>{question.q}</h2>
<input type="text"
value={this.state.value}
onChange={this.handleChange}
/>
<button onClick={this.handleSubmit}>
Submit
</button>
</div>
);

React 将通过 state 更新组件内容,
这会产生隐藏上一个/显示下一个

的效果

下一个问题

Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state

要解决此问题,请使用第二种形式的 setState:

this.setState(prev => {

// Get previous state
const {value, current} = prev;

//If input not empty
if (value.length > 0) {

// Validate answer: true / false
const validation = questions[current].a(value);

//If not last question
return (prev.current < index) ?

//Select next question / reset input
{
current: prev.current + 1,
value:''
} :

// else: Completed!
{ completed: true };

}
});

参见:State Updates May Be Asynchronous

已完成

When all questions are answered, the Madlibs component is called.

{ this.state.completed ? <Madlibs /> : RenderQuestion }

条件

If the condition is true, the element right after && will appear in the output. If it is false, React will ignore and skip it.

condition === true  && element / method

Another method for conditionally rendering elements inline is to use the JavaScript conditional operator:

condition ? true : false

参见:Inline If with Logical && Operator

示例

const QuestionsList = [
{
q: "What's your name?",
a: (answer) => /^[A-Za-z\s]+$/.test(answer),

// Force user to give a correct answer
required: true

},
{
q: "Type a color:",
a: (answer) => {
const colors = ['blue', 'green', 'red', 'yellow', 'black', 'brown', 'orange', 'pink', 'purple', 'white', 'gray']
return colors.includes(answer);
},
required: true
},
];

class Questionary extends React.Component {

constructor(props){
super(props);

//Init state
this.state = {
current: 0,
value:'',
completed: false,
data: []
};

// Bind handlers
this.handleSubmit = this.handleSubmit.bind(this);
this. handleChange = this.handleChange.bind(this);
}

handleChange(event) {
this.setState({value: event.target.value});
}

handleSubmit () {
const {questions} = this.props;
const index = questions.length - 1 ;
let state = {};

this.setState(prev => {
// Vars
const { value, current } = prev;
const question = questions[current];
const validation = question.a(value);

//If input not empty
if (value.length > 0) {

// Debug validation
!validation && console.log("Please enter a valid value!");

//Force user to give the correct answer)
if (question.required && validation == false) return state;

// Data for the template string
let data = prev.data;
data.push(value);

//If not last question
state = (prev.current < index) ?

//Select next question and reset input
{
current: prev.current + 1,
value:'',
data
} :

// else: Completed!
{ completed: true, data };

return state;
}

// Debug input
console.log("Empty input!");
});
}

render() {

// Get all questions
const { questions } = this.props;

//Select question
const question = questions[this.state.current];

// Question component
const RenderQuestion = (
<div>
<h2>{question.q}</h2>
<input type="text"
value={this.state.value}
onChange={this.handleChange}
/>
<button onClick={this.handleSubmit}>
Submit
</button>
</div>
);

// Score component
const RenderTemplates = (
<div>
<h2>Completed!</h2>
<p>
This is the story of
<span>{this.state.data[0]}</span>
and how the
<span>{this.state.data[1]}</span> dragon...
</p>
<p>
<span>{this.state.data[0]}</span> found a
<span>{this.state.data[1]}</span> goblin in the woods and then...
</p>
</div>
);

return (
<div>
{
this.state.completed ?
RenderTemplates : RenderQuestion
}
</div>
);
}
}

ReactDOM.render(<Questionary questions={QuestionsList}/>, document.getElementById("root"));
#root {

font-family: Arial, sans-serif;
color: #252525

}

h2, input[type=text] {
margin: 10px;
}

button {
border: 0;
border-radius: 3px;
background: #416dea;
padding: 5px 10px;
color: #FFF;
font-weight: bold;
border-radius: 3px;
}

p {
padding: 10px;
background: #ddd;
}
p span {
padding: 2px 4px;
margin: 0 10px;
background: #FFF;
color: #416dea;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>
<div id="root"></div>

关于javascript - 提交后 React.js "hide element and reveal next element",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45400191/

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