首页 > 解决方案 > 如何插入
一个javascript字符串

问题描述

我正在尝试显示信息列表,例如在某些日子里诊所的营业时间CompareDialog.js

原始数据存储在一个json文件中,这里是所提供数据的单个元素。

  {
      "type": "GP",
      "properties": {
        //other information
        "DR_NAME": "Dr Philips",
        "ALL_OPENING_HOURS": [
          {
            "day_string": "Monday - Thursday",
            "opening_hours": [
              "8.30AM – 12.30PM",
              "2.00PM – 4.30PM",
              "6.30PM – 9.00PM"
            ]
          },
          {
            "day_string": "Friday",
            "opening_hours": [
              "8.30AM – 12.30PM",
              "2.00PM – 4.30PM"
            ]
          },
          {
            "day_string": "Saturday & Sunday",
            "opening_hours": [
              "8.30AM – 12.30PM"
            ]
          },
          {
            "day_string": "Public Holiday",
            "opening_hours": [
              "Closed"
            ]
          }
        ],

        "FILE_NAME": "Slide1"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          103.77076830515,
          1.38358044593591,
          0
        ]
      }
    }

我能够使用“HTML 中的 JS”语法将每个营业时间按天分开,如GpDialog.js. 信息的显示方式是

Opening Hours:

Monday - Thursday

8.30AM – 12.30PM, 2.00PM – 4.30PM, 6.30PM – 9.00PM

Friday

8.30AM – 12.30PM, 2.00PM – 4.30PM

Saturday & Sunday

8.30AM – 12.30PM

Public Holiday

Closed

我试图重现 in 中的分隔CompareDialog.js,但当前代码将formattedOpeningHoursand存储formattedDirections为字符串,我不知道是否可以使用带有in 的ClinicMap.jsHTML 语法来操作换行符。我也尝试在字符串中插入换行符,但也无法重现从.createDataCompareDialog.jsGpDialog.js

目前,显示的数据CompareDialog.js仍然是一个单一的字符串,如

Monday - Thursday: 9.00AM – 3.30PM, 7.00PM – 9.00PM, Friday: 9.00AM – 3.30PM, Saturday, Sunday & Public Holiday: 9.00AM – 12.30PM

有人可以启发我如何解决这个问题吗?我看到了一篇类似的帖子,其中涉及到文档函数的使用,但不确定它是否适合我的上下文。这是一些相关代码,请随时要求更多说明。

GpDialog.js

import React, { Component } from "react";
import Dialog from "@material-ui/core/Dialog";
import { Link, Redirect } from "react-router-dom";
import Button from "@material-ui/core/Button";
import Grid from "@material-ui/core/Grid";


import {
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle
} from "@material-ui/core";

export class GpDialog extends Component {
  state = {
    open: false,
    redirectTo: null
  };
  handleToggle = () => {
    this.setState({
      open: !this.state.open
    });
  };



  render() {

    const { onClose, selectedGP, ...other } = this.props;
    const { open } = this.state;
    const { clinic } = this.props;
    const handleToggle = () => {
      this.setState({
        open: !this.state.open
      });
    };

    function handleClose() {
      onClose(selectedGP);
    }

    function handleListItemClick(clinic, name) {
      onClose(clinic, name);
      handleToggle();
    }



    if (this.state.redirectTo) {
      return (
        <Redirect to={this.state.redirectTo} />
      );
    }

    return (
      <div>
        <Button variant="outlined" fullWidth="true" onClick={this.handleToggle}>
          {clinic.properties.HCI_NAME}
        </Button>
        <Dialog open={open} onClose={handleToggle}>
          <DialogContent>
            //some other data
            <hr /> Telephone: {clinic.properties.Tel} <hr />
            Applicable subsidies:{" "}
            {clinic.properties.CLINIC_PROGRAMME_CODE.join(", ")}
            <hr />
            Distance:
            {parseFloat(clinic.distance).toFixed(2)}km away
            <hr />
            Doctor: {clinic.properties.DR_NAME}

            <hr />



            <p>Opening Hours:</p>
            <hr />
            {clinic.properties.ALL_OPENING_HOURS.map(period => (
              <p>
                {period.day_string}
                <br />
                {period.opening_hours.join(", ")}
              </p>
            ))}
            <hr />

            <p>Directions:</p>
            {clinic.properties.ALL_DIRECTIONS.map(path => (
              <p>
                {path.transport_string}
                <br />
                {path.directions.join(", ")}
              </p>
            ))}
            <hr />





            <img src={process.env.PUBLIC_URL + `/ClinicPictures/${clinic.properties.FILE_NAME}.png`} 
            alt="clinic picture" style={{ width: "100%" }} />

            <hr />

            <Grid style={{ flexGrow: 1 }} direction="row">
              <Grid container justify="space-between">
                <Grid item>
                  <Button
                    variant="contained"
                    color="primary"
                    onClick={() =>
                      handleListItemClick(clinic, clinic.properties.HCI_NAME)
                    }
                  >
                    <span style={{ color: "white" }}>Add to comparison</span>
                  </Button>
                </Grid>

                <Grid item>
                  <Button
                    variant="contained"
                    style={{ backgroundColor: "#ff7c01" }}
                    onClick={this.handleCompare}
                  >
                    <Link
                      to={{
                        pathname: "/ConfirmClinicChoice",
                        state: {
                          choice: clinic,
                          formData: this.props.formData
                        }
                      }}
                    >
                      <span style={{ color: "white" }}>Select</span>
                    </Link>
                  </Button>
                </Grid>



              </Grid>
            </Grid>
          </DialogContent>
        </Dialog>
      </div>
    );
  }
}

export default GpDialog;

ClinicMap.js

import React, { Fragment, Component } from "react";
import { Map, GoogleApiWrapper, Marker } from "google-maps-react";
import PcDialog from "../PcDialog";
import Button from "@material-ui/core/Button";
import InfoWindowEx from "./InfoWindowEx";
import { Link, Redirect } from "react-router-dom";

const mapStyles = {
  width: "100%",
  height: "100%"
};

export class ClinicMap extends Component {
  state = {
    activeMarker: {},
    selectedPlace: {
      clinic: {
        type: ""
      }
    },
    showingInfoWindow: false
  };

  onMarkerClick = (props, marker) =>
    this.setState({
      activeMarker: marker,
      selectedPlace: props,
      showingInfoWindow: true
    });

  render() {
    const { GP, PC, parentCallback } = this.props;
    const { selectedPlace } = this.state;

    const displayCurrent = (
      <Marker
        clinic={{type: "currentloc"}}
        position={{
          lat: this.props.coord[1],
          lng: this.props.coord[0]
        }}
      />
    );

    const displayGP = GP.map(clinic => {
      clinic.type = "GP";
      clinic.name = clinic.properties.HCI_NAME;
      clinic.price = "$$";
      clinic.rating = "4.3";
      clinic.doctorName = clinic.properties.DR_NAME;


      clinic.formattedOpeningHours = 
        clinic.properties.ALL_OPENING_HOURS.map(period => (
          period.day_string + ":\n" + period.opening_hours.join(",\n")
        ))
        .join(", \n");

      clinic.formattedDirections = 
        clinic.properties.ALL_DIRECTIONS.map(path => (
          path.transport_string + "\n" + path.directions.join(",\n")
        ))
        .join(", \n");



      return (
        <Marker
          key={clinic.id}
          clinic={clinic}
          id={clinic.id}
          icon={"http://maps.google.com/mapfiles/ms/icons/green.png"}
          position={{
            lat: clinic.geometry.coordinates[1],
            lng: clinic.geometry.coordinates[0]
          }}
          onClick={this.onMarkerClick}
        />
      );
    });

    const displayPC = PC.map(clinic => {
      clinic.type = "Polyclinic";
      clinic.name = clinic.Name;
      clinic.price = "$";
      clinic.rating = "4.0";
      return (
        <Marker
          key={clinic.id}
          clinic={clinic}
          id={clinic.id}
          icon={"http://maps.google.com/mapfiles/ms/icons/blue.png"}
          position={{
            lat: clinic.coord[1],
            lng: clinic.coord[0]
          }}
          onClick={this.onMarkerClick}
        >
          <PcDialog clinic={clinic} />
        </Marker>
      );
    });
    return (
      <Map
        google={this.props.google}
        zoom={15}
        style={mapStyles}
        initialCenter={{ lat: this.props.coord[1], lng: this.props.coord[0] }}
      >
        {displayGP}
        {displayPC}
        {displayCurrent}
        {console.log(displayCurrent)}
        <InfoWindowEx
          marker={this.state.activeMarker}
          onClose={this.onInfoWindowClose}
          visible={this.state.showingInfoWindow}
          selectedPlace={selectedPlace}
        >
          {selectedPlace.clinic.type === "GP" ? (
            <div>
              GP: 
              //some other data
              <hr /> Telephone: {selectedPlace.clinic.properties.Tel} <hr />
              Applicable subsidies:{" "}
              {selectedPlace.clinic.properties.CLINIC_PROGRAMME_CODE.join(", ")}
              <hr />
              Distance:
              {parseFloat(selectedPlace.clinic.distance).toFixed(2)}km away
              <hr />


              Doctor: {selectedPlace.clinic.properties.DR_NAME}




              <hr />
              <p>Opening Hours:</p>
              <hr />
              {
                selectedPlace.clinic.properties.ALL_OPENING_HOURS.map(period => (
                  <p>
                    {period.day_string}
                    <br />
                    {period.opening_hours.join(", ")}
                  </p>
                ))
              }
              <hr />

              <p>Directions:</p>
              {
                selectedPlace.clinic.properties.ALL_DIRECTIONS.map(path => (
                  <p>
                    {path.transport_string}
                    <br />
                    {path.directions.join(", ")}
                  </p>
                ))
              }
              <hr />





              <img src={process.env.PUBLIC_URL + `/ClinicPictures/${selectedPlace.clinic.properties.FILE_NAME}.png`}
                alt="clinic picture" style={{ width: "100%" }} />

              <hr />


              <Button>
                <Link
                  to={{
                    pathname: "/ConfirmClinicChoice",
                    state: {
                      choice: selectedPlace.clinic
                    }
                  }}
                >
                  <span>Select</span>
                </Link>
              </Button>


              <Button
                variant="contained"
                color="primary"
                onClick={() =>
                  this.props.callbackFunction(selectedPlace.clinic)
                }
              >
                {console.log(selectedPlace.clinic)}
                <span style={{ color: "white" }}>Add to comparison</span>
              </Button>
            </div>
          ) : selectedPlace.clinic.type === "Polyclinic" ? (
            <div>
              //some other data
              <hr /> Telephone: {selectedPlace.clinic.Tel} <hr /> Distance:{" "}
              {parseFloat(selectedPlace.clinic.distance).toFixed(2)}km away
              <hr />


              <Button>
                <Link
                  to={{
                      pathname: "/ConfirmClinicChoice",
                    state: {
                      choice: selectedPlace.clinic
                    }
                  }}
                >
                  <span>Select</span>
                </Link>
              </Button>


              <Button
                variant="contained"
                color="primary"
                onClick={() =>
                  this.props.callbackFunction(selectedPlace.clinic)
                }
              >
                <span style={{ color: "white" }}>Add to comparison</span>
              </Button>
            </div>
          ) : (
            <div>Input Location</div>
          )}

        </InfoWindowEx>
      </Map>
    );
  }
}

export default GoogleApiWrapper({
  apiKey: ""
})(ClinicMap);

比较对话.js

import React, { Component, Fragment } from "react";
import Dialog from "@material-ui/core/Dialog";
import { Link } from "react-router-dom";
import Button from "@material-ui/core/Button";
import Table from "@material-ui/core/Table";
import TableBody from "@material-ui/core/TableBody";
import TableCell from "@material-ui/core/TableCell";
import TableHead from "@material-ui/core/TableHead";
import TableRow from "@material-ui/core/TableRow";
import TableFooter from "@material-ui/core/TableFooter";
import ExpandMoreIcon from "@material-ui/icons/ExpandMore";
import MyButton from "../../util/MyButton";

import {
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Typography
} from "@material-ui/core";
import { maxWidth, fontSize } from "@material-ui/system";
export class CompareDialog extends Component {
  state = {
    open: false,
    priceOpen: false,
    userNationality: this.props.formData.nationality,
    userAge: this.props.formData.age,
    userSubsidyType: this.props.formData.subsidyType
  };
  handleToggle = () => {
    this.setState({
      open: !this.state.open
    });
  };
  handlePriceToggle = () => {
    this.setState({
      priceOpen: !this.state.priceOpen
    });
  };
  render() {
    const {
      open,
      priceOpen,
      userNationality,
      userAge,
      userSubsidyType
    } = this.state;
    const { clinicOne, clinicTwo, formData } = this.props;
    function createData(name, gp, pc) {
      return { name, gp, pc };
    }
    const rows = [
      createData(
        <span style={{ fontWeight: "bold" }}>Name</span>,
        <span style={{ fontWeight: "bold" }}>{clinicOne.name}</span>,
        <span style={{ fontWeight: "bold" }}> {clinicTwo.name}</span>
      ),
      createData(
        "Distance",
        parseFloat(clinicOne.distance).toFixed(2),
        parseFloat(clinicTwo.distance).toFixed(2)
      ),
      createData("Price", clinicOne.price, clinicTwo.price),
      createData("Ratings", clinicOne.rating, clinicTwo.rating),
      createData("Doctor name", ((clinicOne.type === "GP") ? clinicOne.doctorName : ""),
      ((clinicTwo.type === "GP") ? clinicTwo.doctorName : "")),
      createData("Opening hours", ((clinicOne.type === "GP") ? clinicOne.formattedOpeningHours : ""),
        ((clinicTwo.type === "GP") ? clinicTwo.formattedOpeningHours : "")),
      createData("Directions", ((clinicOne.type === "GP") ? clinicOne.formattedDirections : ""),
        ((clinicTwo.type === "GP") ? clinicTwo.formattedDirections : "")),

    ];

    //some data irrelevant to the problem
    const handleToggle = () => {
      this.setState({
        open: !this.state.open
      });
    };
    const handlePriceToggle = () => {
      this.setState({
        priceOpen: !this.state.priceOpen
      });
    };
    return clinicOne === null || clinicTwo === null ? (
      "Please select 2 clinics for comparison."
    ) : (
      <div>
        <Button
          variant="contained"
          style={{ backgroundColor: "#ff7c01" }}
          onClick={handleToggle}
        >
          Compare!
        </Button>
        <Dialog
          style={{ fontSize: "1vw" }}
          open={open}
          onClose={handleToggle}
          maxWidth="lg"
        >
          <DialogContent>
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell> </TableCell>
                  <TableCell align="right">{clinicOne.type} </TableCell>
                  <TableCell align="right">{clinicTwo.type} </TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {rows.map(row => (
                  <TableRow key={row.name}>
                    <TableCell component="th" scope="row">
                      {row.name === "Price" ? (
                        <Fragment>
                          Price
                          <MyButton
                            onClick={handlePriceToggle}
                            tip="More Details"
                          >
                            <Typography variant="subtitle1">Expand</Typography>
                            <ExpandMoreIcon />
                          </MyButton>
                          <Dialog open={priceOpen} onClose={handlePriceToggle}>
                            <DialogContent>
                              <p
                                style={{
                                  fontWeight: "bold",
                                  textDecoration: "underline"
                                }}
                              >
                                Cost Breakdown
                              </p>
                              <Table>
                                <TableHead>
                                  <TableRow>
                                    <TableCell />
                                    <TableCell
                                      style={{ minWidth: 200, maxWidth: 200 }}
                                      align="right"
                                    >
                                      {" "}
                                      {clinicOne.type}
                                    </TableCell>

                                    <TableCell
                                      style={{ minWidth: 200, maxWidth: 200 }}
                                      align="right"
                                    >
                                      {clinicTwo.type}
                                    </TableCell>
                                  </TableRow>
                                </TableHead>
                                <TableBody>
                                  <TableRow>
                                    <TableCell component="th" scope="row">
                                      <span style={{ fontWeight: "bolder" }}>
                                        Name
                                      </span>
                                    </TableCell>
                                    <TableCell component="th" scope="row">
                                      <span style={{ fontWeight: "bolder" }}>
                                        {clinicOne.name}
                                      </span>
                                    </TableCell>
                                    <TableCell component="th" scope="row">
                                      <span style={{ fontWeight: "bolder" }}>
                                        {" "}
                                        {clinicTwo.name}
                                      </span>
                                    </TableCell>


                                  </TableRow>
                                  {priceRows.map(row => (
                                    <TableRow key={row.name}>
                                      <TableCell component="th" scope="row">
                                        {row.name}
                                      </TableCell>
                                      <TableCell align="right">
                                        {clinicOne.type === "GP"
                                          ? row.gp
                                          : row.pc}
                                      </TableCell>
                                      <TableCell align="right">
                                        {clinicTwo.type === "GP"
                                          ? row.gp
                                          : row.pc}{" "}
                                      </TableCell>
                                    </TableRow>
                                  ))}
                                </TableBody>
                              </Table>
                            </DialogContent>
                          </Dialog>
                        </Fragment>
                      ) : (
                        <Fragment>{row.name}</Fragment>
                      )}
                    </TableCell>
                    <TableCell align="right">{row.gp}</TableCell>
                    <TableCell align="right">{row.pc} </TableCell>
                  </TableRow>
                ))}
              </TableBody>
              <TableFooter>
                <TableCell align="right">
                  <Button />
                </TableCell>


                <TableCell align="right">
                  <Button
                    variant="contained"
                    style={{ backgroundColor: "#ff7c01" }}
                  >
                    <Link
                      to={{
                        pathname: "/ConfirmClinicChoice",
                        state: {
                          choice: clinicOne,
                          formData: this.props.formData
                        }
                      }}
                    >
                      <span style={{ color: "white" }}>Select</span>
                    </Link>
                  </Button>
                </TableCell>



                <TableCell align="right">
                  <Button
                    // style={{ fontSize: "1vw" }}
                    variant="contained"
                    style={{ backgroundColor: "#ff7c01" }}
                  >
                    <Link
                      to={{
                        pathname: "/ConfirmClinicChoice",
                        state: {
                          choice: clinicTwo,
                          formData: this.props.formData
                        }
                      }}
                    >
                      <span style={{ color: "white" }}>Select</span>
                    </Link>
                  </Button>
                </TableCell>
              </TableFooter>
            </Table>
          </DialogContent>
        </Dialog>
      </div>
    );
  }
}

export default CompareDialog;

更新:

尝试改变

  createData("Opening hours", ((clinicOne.type === "GP") ? clinicOne.formattedOpeningHours : ""),
    ((clinicTwo.type === "GP") ? clinicTwo.formattedOpeningHours : "")),

  createData(
        "Opening hours",
        clinicOne.type === "GP" ? (
          <div
            dangerouslySetInnerHTML={{
              __html: clinicOne.formattedOpeningHours
            }}
          />
        ) : (
          ""
        ),
        clinicTwo.type === "GP" ? (
          <div
            dangerouslySetInnerHTML={{
              __html: clinicTwo.formattedOpeningHours
            }}
          />
        ) : (
          ""
        )
      ),

并且输出与以前相同。

标签: javascripthtmlreactjs

解决方案


你在找这个吗?

render() {
    let str = 'Welcom </br> to </br> stack </br> overflow';
    return (
      <div>
       <div dangerouslySetInnerHTML={{ __html: str }} />
      </div>
    );
  }

演示


推荐阅读