简体   繁体   English

在 JSX 中访问 Map Function 之外的值

[英]Access value outside Map Function in JSX

Newbie question here.新手问题在这里。 I'm not sure how can access slide.title value outside map function scope in JSX and place somewhere else.我不确定如何在 JSX 中访问map function scope 之外的 slide.title 值并放置在其他地方。

{
  bases.map((slide, index) => {
    return (
      <div className={index === base ? "slide active" : "slide"} key={index}>
        {index === base && (
          <img alt={slide.title} className="skin" src={slide.url} />
        )}
        {index === base && <p>{slide.title}</p>}
      </div>
    );
  });
}

Lets say I want this actual slide.title use in paragraph tag outside this function.比方说我想在这个 function 之外的段落标记中使用这个实际的 slide.title。

<p>{slide.title}</p>

I suppose I can store in state and reuse it, but really I don't know how.我想我可以存储在 state 中并重新使用它,但我真的不知道该怎么做。

Thanks in advance提前致谢

Just use bracket notation to look up the base index in the array to get the title there:只需使用括号表示法查找数组中的base索引即可获得标题:

<p>{bases[base]?.title}</p>

I think a state would be your best bet.我认为 state 是您最好的选择。

I like to use a reducer because it allows for multiple states.我喜欢使用 reducer,因为它允许多个状态。

import {useReducer} from 'react';
const initialState = {
title = ""
}
const reducer = (state, newState) => ({...state, ...newState});
const [state, setState] = useReducer(reducer, initialState);

//then when you do have access to the slide.title just 
setState({title: slide.title});

This would let you add multiple state items, just by adding them into the initial state const at the top.这将允许您添加多个 state 项,只需将它们添加到顶部的初始 state const 中即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM