简体   繁体   English

Next.js 使用 getServerSideProps 如何将道具从页面传递到组件?

[英]Next.js using getServerSideProps how do i pass props from page to components?

I am trying to fetch coingecko-api to access live price of bitcoin.我正在尝试获取coingecko-api以访问比特币的实时价格。 I am trying to pass return props of getServerSideProps to my <CalculatorBuy /> component which is the part of <Main /> component.我正在尝试将 getServerSideProps 的返回道具传递给我的<CalculatorBuy />组件,该组件是<Main />组件的一部分。 I was trying to import async function in calculatorbuy.js but i'm getting undefined object.我试图在calculatorbuy.js中导入异步function,但我得到未定义的object。 How to pass props from index.js to main.js and calculatorbuy.js components.如何将 props 从index.js传递到main.jscalculatorbuy.js组件。 In index.js everything work like a charm but i would like to use props value directly in components.在 index.js 中,一切都像魅力一样工作,但我想直接在组件中使用 props 值。

index.js

export default function Home(props) {

  const {data} = props.result;
  console.log(data);

  return (
    <div className="container">
      <Head>
        <title>Buy BTC</title>
        <link rel="icon" href="/favicon.ico" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0"></meta>
      </Head>
      <Header />

      <Main />

      <Footer />
      <style jsx> {`
        .container {
          min-height: 100vh;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
        }
      `} </style>
    </div>
  )
}

export async function getServerSideProps(context) {
  const result = await coinGeckoClient.simple.price({
      ids: "bitcoin",
      vs_currencies: "eur",
  });
  return {
      props: {
          result,
      },
  }
  
}
main.js

import React, { useState } from 'react';
import Button from '@material-ui/core/Button';
import Calculatorbuy from './calculatorbuy.js'
import Calculatorsell from './calculatorsell.js'
  

export default function Main() {
    const [ showMe, setShowMe ] = useState(true);
    function toggle (){
        if  (!showMe) {
            setShowMe(true);
        }
        else {
            setShowMe(true);
        }
    }
    function toggle2 (){
        if  (showMe) {
            setShowMe(false);
        }
        else {
            setShowMe(false);
        }
    }
    
    return (
        <main className="main">
            <div className="box">
                <div className="buttons">

                    <Button onClick={toggle} variant="outlined" color="primary" style={{width: 120, marginRight: 10}}>
                        KUP
                    </Button>
                    <Button onClick={toggle2} variant="outlined" color="secondary" style={{width: 120, marginRight: 10}}>
                        SPRZEDAJ
                    </Button>
                    <Button variant="outlined" color="default" style={{width: 120,}}>
                        HISTORIA
                    </Button>
                </div>
                <div style={{ display: showMe?"block":"none" }}>
                    <Calculatorbuy />
                </div>
                <div style={{ display: !showMe?"block":"none" }}>
                    <Calculatorsell />
                </div>
            </div>
            <div className="room-for-socials"></div>
import React, { useState } from 'react';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import Livebsv from './livebsv.js';



export default function Calculatorbuy() {
    const [value, setValue] = useState(0);
   
    return (
        <form className="calculator" noValidate autoComplete="off">
            <div>
                <Livebsv />
            </div>
            <div className="typebox">
                <div className="textfield">
                    <TextField error={false} id="outlined-number" label="PLN" helperText="Min. wartość 100zł"  
                    type="tel"
                    value={value}
                    InputProps={{ 
                        inputProps: { min: "100", max: "5000", step: "0.01" } 
                    }}
                    variant="outlined"
                    onKeyPress={(e) => {
                        if (!/[0-9]/.test(e.key)) {
                          e.preventDefault();
                        }
                      }}
                    onChange={(e) => setValue(e.currentTarget.value)}
                    onKeyPress={(e) => {
                        if (!/[0-9]/.test(e.key)) {
                          e.preventDefault();
                        }
                      }}
                    onBlur={(e) => {
                      if (e.currentTarget.value > 0 & e.currentTarget.value < 100 ) 
                        setValue(100);
                      else if (e.currentTarget.value > 5000) 
                        setValue(5000);
                    }}
                    />
                </div>
                <div className="textfield">
                    <TextField disabled id="outlined-disabled" value={(value).toFixed(8)} label="BSV" variant="outlined" 


You started well by loading the result on index.js(getServerSideProps).通过在 index.js(getServerSideProps) 上加载结果,您开始做得很好。

Then, to pass the data to Main, you have to add it as a property for the component:然后,要将数据传递给 Main,您必须将其添加为组件的属性:

<Main data={data} />

Now, as Main expects a parameter, it has to be defined in main.js:现在,由于 Main 需要一个参数,它必须在 main.js 中定义:

export default function Main(props) {
    const data = props.data;
    ...
}

Then, for the Calculatorbuy component you have to do the same like on Main.然后,对于 Calculatorbuy 组件,您必须在 Main 上执行相同的操作。 Define the props and use it.定义道具并使用它。

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

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