gpt4 book ai didi

javascript - 为什么内容只有在 onChange 之后才呈现?

转载 作者:行者123 更新时间:2023-12-02 23:49:41 26 4
gpt4 key购买 nike

我正在使用rc-slider从数组中获取一堆值并将它们呈现在我的组件中。

const array = ["Hey", "Ho", "Me", "Too", "See"]
class App extends Component {
state = { sliderValues: [0, 1, 2, 3, 4] };

handleChange = sliderValues => {
this.setState({ sliderValues }, () => console.log(array[this.state.sliderValues]));
};

render() {
const renderContent = array.map((value, index) => {
console.log(value, 'value')
console.log(index, 'index')
if (index === this.state.sliderValues) {
return (
<div>
<h1>{value}</h1>
</div>
)
}
})
return (
<div>
{renderContent}
<Slider onChange={this.handleChange} min={0} max={4} defaultValue={this.state.sliderValues} marks={{ 0: 250, 1: 500, 2: 750, 3: 1000, 4: 1500 }} step={null} />
</div>
)
}
}

我只想一次显示数组中的一项。除了初始渲染之外,一切正常。您会注意到,只有在与 <Slider />. 交互后,该组件才会呈现自身。 。

这是为什么?

Codesandbox

最佳答案

    import React, {Component} from "react";
import ReactDOM from "react-dom";
import Slider from 'rc-slider'
import "./styles.css";

const array = ["Hey", "Ho", "Me", "Too", "See"]
class App extends Component {
// you need to provide an initial value to be rendered at the first time
state = { sliderValues: 0 };

handleChange = sliderValues => {
this.setState({ sliderValues }, () => console.log(array[this.state.sliderValues]));
};

render() {
const renderContent = array.map((value, index) => {
console.log(value, 'value')
console.log(index, 'index')
if (index === this.state.sliderValues) {
return (
<div key={value}>
<h1>{value}</h1>
</div>
)
}
})
return (
<div>
{renderContent}
<Slider onChange={this.handleChange} min={0} max={4} defaultValue={this.state.sliderValues} marks={{ 0: 250, 1: 500, 2: 750, 3: 1000, 4: 1500 }} step={null} />
</div>
)
}
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

关于javascript - 为什么内容只有在 onChange 之后才呈现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55695598/

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